How to compare string sizes in python

Release: 2019-07-08 09:05:52
Original
14175 people have browsed it

How to compare string sizes in python

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
Copy after login

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)
Copy after login

Instance

>>> import operator
>>> operator.eq('hello', 'name');
False
>>> operator.eq('hello', 'hello');
True
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template