Comparing Strings


if cmpStr.upper() == upperStr.upper():     print upperStr + " Matches " + cmpStr

Comparing strings in Python is best accomplished using a simple logical operation. For example, to determine whether a string matches another string exactly, you would use the is equal or == operation. You can also use other logical operations such as >= or < to determine a sort order for several strings.

Python provides several methods for string objects that help when comparing. The most commonly used are the upper() and lower() methods, which return a new string that is all upper- or lowercase, respectively.

Another useful method is the capitalize() method, which returns a new string with the first letter capitalized. There is also a swapcase() that will return a new string with exactly the opposite casing for each character.

cmpStr = "abc" upperStr = "ABC" lowerStr = "abc" print "Case Sensitive Compare" if cmpStr == lowerStr:     print lowerStr + " Matches " + cmpStr if cmpStr == upperStr:     print upperStr + " Matches " + cmpStr print "\nCase In-Sensitive Compare" if cmpStr.upper() == lowerStr.upper():     print lowerStr + " Matches " + cmpStr if cmpStr.upper() == upperStr.upper():     print upperStr + " Matches " + cmpStr


comp_str.py

Case Sensitive Compare abc Matches abc Case In-Sensitive Compare abc Matches abc ABC Matches abc


Output from comp_str.py code



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net