How It Works

The number on the left is compared to the number on the right. You can compare letters, too. A few conditions exist where this might not do what you expect, such as trying to compare letters to numbers. (The question just doesn't come up in many cases, so what you expect and what Python expects is probably not the same.) The values of the letters in the alphabet run roughly this way: A capital "A" is the lowest letter. " B 11 is the next, followed by " C 1 1 and so on until " Z 11. This is followed by the lowercase letters, with " a11 being the lowest lowercase letter and " z 11 the highest. However, " a 1 1 is higher than " > 1 1 :

>>> "a" > "b" False

>>> "A" > "b" False

>>> "A" > "a" False

>>> "Z" > "a" False

If you want to compare two strings that are longer than a single character, Python will look at each letter until it finds one that's different. When that happens, the outcome will depend on that one difference. If the strings are completely different, the first letter will decide the outcome:

>>> "Zebra" > "aardvark" False

>>> "Zebra" > "Zebrb" False

>>> "Zebra" < "Zebrb" True

You can avoid the problem of trying to compare two words that are similar but have differences in capitalization by using a special method of strings called lower, which acts on its string and returns a new string with all lowercase letters. There is also a corresponding upper method. These are available for every string in Python:

>>> "Pumpkin" == "pumpkin" False

>>> "Pumpkin".lower() == "pumpkin".lower() True

>>> "Pumpkin".upper() == "pumpkin".upper() True

Note that you could have also written the preceding code in the following manner:

>>> "Pumpkin".lower() == "pumpkin" True

Because "pumpkin" is already lowercase, there is no real need to change it, though doing so may be safer. For instance, if someone types in a string incorrectly, capitalizing one of the letters in one of the strings, converting them both would solve any errors. Observe the following:

>>> "Pumpkin".lower() == "puMpkin" False

>>> "Pumpkin".lower() == "puMpkin".lower() True

When you have a string referenced by a name, you can still access all of the methods that strings normally have:

'Calabash'

'calabash'

'CALABASH'

0 0