在 Python 中如何将字符串转换为整数
应用开发 2025-10-09 15:30:49
0
类似于内置的中何转换 str() 方法,Python 语言中有一个很好用的将字 int() 方法,可以将字符串对象作为参数,符串并返回一个整数。为整
用法示例:
# Here age is a string object age = "18" print(age) # Converting a string to an integer int_age = int(age) print(int_age)输出:
18 18尽管输出结果看起来相似,中何转换但是将字,请注意第一行是符串字符串对象,而后一行是云南idc服务商为整整数对象。在下一个示例中将进一步说明这一点:
age = "18" print(age + 2)输出:
Traceback (most recent call last): File "<stdin>",中何转换 line 1, in <module> TypeError: cannot concatenate str and int objects通过这个报错,你应该明白,将字你需要先将 age 对象转换为整数,符串然后再向其中添加内容。为整
age = "18" age_int = int(age) print(age_int + 2)输出:
20但是中何转换,请记住以下特殊情况:
浮点数(带小数部分的将字整数)作为参数,将返回该浮点数四舍五入后最接近的符串整数。香港云服务器例如:print(int(7.9)) 的打印结果是 7。另一方面,print(int("7.9")) 将报错,因为不能将作为字符串对象的浮点数转换为整数。 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 7.9 单词作为参数时,将返回相同的错误。例如,站群服务器print(int("one")) 将返回: Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: one