python中input()转换字符串

563次阅读
没有评论

python中input()转换字符串

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()转换字符串的方法,希望能对大家有所帮助。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-02发表,共计489字。
新手QQ群:570568346,欢迎进群讨论 Python51学习