Python: Convert String to Number

In Python, you can use the built-in int() function to convert a string to an integer and the float() function to convert a string to a float. Here is an example code:

# 将字符串转换为整数
str_number = "42"
int_number = int(str_number)
print(int_number)  # 输出: 42

# 将字符串转换为浮点数
str_float = "3.14"
float_number = float(str_float)
print(float_number)  # 输出: 3.14

Please note that if the string is not a valid numeric representation, the conversion will raise a ValueError exception. Therefore, it is best to ensure that the string contains valid numbers before performing the conversion.

bannerAds