• 技术文章 >Python技术 >Python基础教程

    python中input()转换字符串

    小妮浅浅小妮浅浅2021-03-06 16:18:32原创3246

    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基础教程

    专题推荐:python,input
    品易云
    上一篇:input在python中的使用注意 下一篇:python中ssl认证是什么?

    相关文章推荐

    • Python input()函数:获取用户输入的字符串• python input() 类型是什么• Python实用之input()和raw_input()的区别• python中raw_input()函数如何使用?• 如何使用python中的input()函数?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网