在 Python 中如何将字符串转换为整数

类似于内置的 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) 

输出:

  1. 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' 

 想要小游戏的或者Python资料的可以扫码获取

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值