String

string转int,使用这些技巧轻松搞定

小樊
85
2024-06-27 13:50:19
栏目: 编程语言

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

0
看了该问题的人还看了