How to compare two string values in Python
Compare two string values
Strings are compared according to their order when sorted alphabetically.
print "alpha" < "beta"
str1 = 'abc'# from w ww . java2s .co m
str2 = 'lmn'
str3 = 'xyz'
print str1 < str2
print str2 != str3
print str1 < str3 and str2 == 'xyz'
The code above generates the following result.
To ignore the difference between uppercase and lowercase letters, use the string methods upper or lower.
print 'java2s.com'.lower() == 'JAVA2s.com'.lower()
The code above generates the following result.
To compare strings case sensitively.
cmpStr = "abc"# from w ww. j a v a 2 s .c om
upperStr = "ABC"
lowerStr = "abc"
print "Case Sensitive Compare"
if cmpStr == lowerStr:
print lowerStr + " Matches " + cmpStr
if cmpStr == upperStr:
print upperStr + " Matches " + cmpStr
The code above generates the following result.
cmp()
cmp()
function performs a lexicographic
(ASCII value-based) comparison for strings.
str1 = 'abc'# www. java2 s.com
str2 = 'lmn'
str3 = 'xyz'
print cmp(str1, str2)
print cmp(str3, str1)
print cmp(str2, 'lmn')
The code above generates the following result.