品易云推流 关闭
文章详情页
文章 > Python基础教程 > python中input()转换字符串

python中input()转换字符串

头像

小妮浅浅

2021-03-06 16:18:324146浏览 · 0收藏 · 0评论

1、如果只想打印输入,这一点问题都没有;但如果你试图将输入作为数字使用,就会引发错误:

>>> age = input("How old are you? ")
How old are you? 21
>>> age >= 18
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() >= int()

试图将输入用于数值比较时,Python会引发错误,因为它无法将字符串和整数进行比较:不能将存储在age中的字符串'21'与数值18进行比较。

2、为解决这个问题,可使用函数int(),它让Python将输入视为数值。函数int()将数字的字符串表示转换为数值表示,如下所示:

>>> age = input("How old are you? ")
How old are you? 21
>>> age = int(age)
>>> age >= 18
True

以上就是python中input()转换字符串的方法,希望能对大家有所帮助。更多Python学习指路:python基础教程

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图