类似于内置的 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
尽管输出结果看起来相似,但是,请注意第一行是字符串对象,而后一行是整数对象。在下一个示例中将进一步说明这一点:
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'
发表评论 取消回复