In our last article we left off discussing ways to manipulate strings in Python, like concatenating, repeating, escape characters, and so forth. In this episode we will pick up where we left off and learn some more ways to work with strings, starting with the comparison method.
It's true; Python is a size queen. It's obsessed with comparing strings, numbers, you name it. It may not make a lot of sense, though, as to how Python sees the value of different strings (uppercase Z is less than lowercase A).
To compare the size of strings, we use the < and > comparison operators, like so:
(type each of these lines at the command prompt)
'A' < 'x'
'X' > 'x'
'1' > 'z'
'$' > 'b'
'$' < '#'
It should return a True or False, depending upon whether or not the comparison is...well, true or false.
You can also try these...
'apples' > 'Apples'
'Fred' > 'fReD'
'11111' > '22222'
And of course you can use Python to compare movies as well:
'Star Trek' > 'Star Wars'
'The Matrix' > 'Star Wars'
'The Matrix' > 'Any Movie'
See? Python sure does know its movies...
The rules for which strings are bigger is like so:
Letters at the start of the alphabet are smaller than those at the end
Capital letters are smaller than lowercase letters
Numbers are smaller than letters
Punctuation marks (aside from curly braces, pipe characters, and the tilde) are smaller than numbers and letters.