Рядок в число

int, float, isdecimal, isdigit, isnumeric

Чи є рядок числом? - isdecimal(), isdigit(), isnumeric()

pin = "523"
# checks if every character of pin is numeric 
print(pin.isnumeric())  # True

String Type

Example

Python .isdecimal()

Python .isdigit()

Python .isnumeric()

Base 10 Numbers

'0123'

True

True

True

Fractions and Superscripts

'⅔', '2²'

False

True

True

Roman Numerals

'ↁ'

False

False

True

https://datagy.io/python-isdigit/

Перетворення рядка на ціле число - int()

str_a = '50'
b = 10
c = int(str_a) + b
print ("The value of c = ",c)  

Але не можна використати int, якщо число в рядку не ціле!

strn = '-12,345678'
print( int( strn.replace(',', '.') ) )             # error!
print( round( float( strn.replace(',', '.') ) ) )  # -12

Перетворення рядка на число з плаваючою точкою - float()

str_a = '50.85'
b = 10.33
c = float(str_a) + b
print ("The value of c = ",c)

Як бути, якщо користувач введе кому замість крапки?

strn = '-12,345678'
print( float( strn.replace(',', '.') ) )              # -12.345678
print( round( float( strn.replace(',', '.') ), 2 ) )  # -12.35 (з округленням)

Last updated