Home  >  Article  >  Backend Development  >  How to compare string sizes in python

How to compare string sizes in python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-22 11:57:1616211browse

Python's string comparison is similar to Java, and also requires a comparison function, and the == symbol cannot be used. Use the cmp() method to compare two objects. If they are equal, 0 will be returned. If the former is greater than the latter, 1 will be returned. If they are less, -1 will be returned.

How to compare string sizes in python

Example:

a = "abc"
b = "abc"
c = "aba"
d = "abd"
print cmp(a,b)
print cmp(a,c)
print cmp(a,d)

Return

0
1
-1

Related recommendations: "Python Video Tutorial

Note:

The cmp function has been removed from python3.

You can use == to compare strings, and the effect is the same as the cmp function. You can also use is.

>>> a='abc'
>>> b='abc'
>>> a is b
True
>>> id(a) == id(b)
True
>>>

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!

Statement:
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