- 使用int()函数将字符串转换为整数
str_number = "123" int_number = int(str_number) print(int_number)
- 使用float()函数将字符串转换为浮点数
str_number = "123.45" float_number = float(str_number) print(float_number)
- 使用算术运算符将字符串转换为整数
str_number = "123" int_number = 0 for char in str_number: int_number = int_number * 10 + int(char) print(int_number)
- 使用正则表达式提取数字并转换为整数
import re str_number = "123abc" int_number = int(re.search(r'\d+', str_number).group()) print(int_number)