简体   繁体   中英

Python: What is the equivalent of PHP “==”

The question says it.

Here's a little explanation.

In PHP. "==" works like this

2=="2" (Notice different type)
// True

While in python:

2=="2"
// False
2==2
// True

The equivalent for python "==" in php is "==="

2===2
//True
2==="2"
//False

Million dollar question. What is php "==" equivalent to in python?

Python doesn't coerce between types the way PHP does, mostly .

You'll have to do it explicitly:

2 == int('2')

or

str(2) == '2'

Python coerces numeric types (you can compare a float with an integer), and Python 2 also auto-converts between Unicode and byte string types (to the chagrin of many).

There isn't one. You need to convert types before checking for equality. In your example, you could do

2==int("2")

There is no equivalent.

The difference is simply that Python is strong-typed where PHP is not, so a comparison between two types in Python would always return false. Unless you explicitly cast to the type of the other part of the comparison of course.

你也可以

str(2) == "2"

so here is the equivalent to php's ==

def php_cmp(a, b):
    if a is None and isinstance(b, basestring):
        a = ""
    elif b is None and isinstance(a, basestring):
        b = ""
    if a in (None, False, True) or b in (None, False, True):
        return bool(a) - bool(b)
    if isinstance(a, (basestring, int, long, float)) and isinstance(b, (basestring, int, long, float)):
        try:
            return cmp(float(a), float(b))
        except ValueError:
            return cmp(a,b)
    if isinstance(a, (tuple,list)) and isinstance(b, (tuple,list)):
        if len(a) != len(b):
            return cmp(len(a),len(b))
        return cmp(a,b)
    if isinstance(a, dict) and isinstance(b, dict):
        if len(a) != len(b):
            return cmp(len(a),len(b))
        for key in a:
            if key not in b:
                raise AssertionError('not compareable')
            r = cmp(a[key], b[key])
            if r: return r
        return 0
    if isinstance(a, (basestring, int, long, float)):
        return 1
    if isinstance(b, (basestring, int, long, float)):
        return -1
    return cmp(a,b)

def php_equal(a, b):
    return php_cmp(a,b) == 0

Test:

>>> php_equal(2, '2')
True

Due to a different object model and array implementation this is not 100% correct, but should give you some idea which problems might occur with automatically converting types for comparison.

May be this's something similar:

x = 5
y = "5"

str(x) == str(y)
True

str(2) == str("2")
True

The best answer one can give you is to avoid PHP-like comparison. Anyway, it leads you to hard-to-find errors and hours spent on debugging.

But it's okay if you want to write your own PHP interpreter in Python.

You probably want to cast variables first and compare them after. If you program fails on casting, you run into errors earlier preventing further damage.

Additional note

As an add-on to Martijn's answer ... since Python does not do implicit type coercion like PHP, you can use:

 type(2)

or

 type("2") 

or

  type(<expression>)

if you need to know the relevant type that Python uses internally, in order to do your expressly specified type coercion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM