转换为数字

基本类型 / 字符串

from locale import atof

# to Int
str_number = "42"
number = int(str_number)

# to Double and Float
# the first method
str_pi = "3.14"
pi_float = float(str_pi)

# the second method: locale-aware, same as float in the C locale
str_exp = "2.71828"
exp = atof(str_exp)

# the third method
str_half = "0,5"
half = float(str_half.replace(",", "."))

# Wrong text: ValueError, not 0 or None
try:
    float(str_half)
except ValueError as error:
    print(f"{error = }")

# A decimal string is not an int
try:
    int(str_pi)
except ValueError as error:
    print(f"{error = }")

print(f"{number = }")
print(f"{pi_float = }")
print(f"{exp = }")
print(f"{half = }")