Python如何比较字符串和整数? [英] How can Python compare strings with integers?

查看:209
本文介绍了Python如何比较字符串和整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

a = '1'
if a == 1:
    print 'yes'
else:
    print 'no'

我们得到输出为 no

Python如何在此处将字符串值与int值进行比较(如果a == 1 )?在C语言中,这样的比较会产生错误,因为这是在比较不同类型。

How is Python comparing a string value to an int here (if a == 1)? In C such a comparison would give an error because this is comparing different types.

推荐答案

Python不是C。与C不同,Python支持任意类型之间的相等性测试。

Python is not C. Unlike C, Python supports equality testing between arbitrary types.

这里没有方法,字符串不支持对整数的相等性测试,整数不支持对字符串的相等性测试。因此,Python退回到默认的身份测试行为,但是对象是不是同一对象,因此结果是 False

There is no 'how' here, strings don't support equality testing to integers, integers don't support equality testing to strings. So Python falls back to the default identity test behaviour, but the objects are not the same object, so the result is False.

请参见 参考文档的值比较部分


相等性比较的默认行为( == != )是基于对象的身份的。因此,具有相同身份的实例的相等比较会导致相等,而具有不同身份的实例的相等比较会导致不平等。这种默认行为的动机是希望所有对象都是自反的(即 x是y 暗示 x == y )。

The default behavior for equality comparison (== and !=) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e. x is y implies x == y).

如果要将整数与包含数字的字符串进行比较,则需要将字符串转换为整数或整数所以是一个字符串,然后比较。

If you wanted to compare integers to strings containing digits, then you need to convert the string to an integer or the integer so a string, then compare.

这篇关于Python如何比较字符串和整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆