【问题标题】:How to compare string and integer in python?如何在python中比较字符串和整数?
【发布时间】:2013-07-15 19:00:39
【问题描述】:

我有这个简单的 python 程序。我运行它并打印yes,而事实上我希望它不会打印任何东西,因为14 不大于14

我看到了这个related 问题,但它不是很有帮助。

#! /usr/bin/python

import sys

hours = "14"

if (hours > 14):
        print "yes"

我做错了什么?

【问题讨论】:

    标签: python comparison


    【解决方案1】:

    使用int将字符串转换为整数:

    hours = int("14")
    
    if (hours > 14):
            print "yes"
    

    在CPython2中,比较两个不同类型的非数值对象时,通过比较类型的名称来进行比较。由于'int' < 'string'任何 int 都小于任何字符串

    In [79]: "14" > 14
    Out[79]: True
    
    In [80]: 14 > 14
    Out[80]: False
    

    这是一个经典的 Python 陷阱。在 Python3 中,这个缺陷已得到纠正——比较不同类型的非数字对象默认会引发 TypeError。

    作为explained in the docs:

    CPython 实现细节:不同类型的对象,除了 数字按其类型名称排序;相同类型的对象 不支持正确比较的按地址排序。

    【讨论】:

      【解决方案2】:

      我认为最好的方法是使用 int(hours)hours 转换为整数。

      hours = "14"
      
      if int(hours) > 14:
          print("yes")```
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-03
        • 1970-01-01
        • 2023-02-05
        • 2015-09-06
        • 1970-01-01
        相关资源
        最近更新 更多