Python's string comparison is similar to Java's. It also requires a comparison function and cannot use the == symbol. Use the cmp() method to compare two objects. If they are equal, 0 is returned, if the former is greater than the latter, 1 is returned, and if less than the latter, -1 is returned.
a = "abc" b = "abc" c = "aba" d = "abd" print cmp(a,b) print cmp(a,c) print cmp(a,d) //返回 0 1 -1
There is no cmp function in the Python3.X version. If you need to implement comparison Function requires the introduction of the operator module, which is suitable for any object. The methods included are:
operator.lt(a, b) operator.le(a, b) operator.eq(a, b) operator.ne(a, b) operator.ge(a, b) operator.gt(a, b) operator.__lt__(a, b) operator.__le__(a, b) operator.__eq__(a, b) operator.__ne__(a, b) operator.__ge__(a, b) operator.__gt__(a, b)
Instance
>>> import operator >>> operator.eq('hello', 'name'); False >>> operator.eq('hello', 'hello'); True
Note: == can be used in python3 to compare two strings, and == in java represents equality with different meanings.
For more Python related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of How to compare string sizes in python. For more information, please follow other related articles on the PHP Chinese website!