String Comparison

The comparison operators work on strings. To see if two strings are equal:
>>> if word == 'hello':
...    print 'Say hello to my little friend.'
...
Say hello to my little friend.
Other comparison operations are useful for putting words in alphabetical order:
>>> word = 'Pineapple'
>>> if word < 'hello':
...    print 'Your word,' + word + ', comes before hello.'
... elif word > 'hello':
...    print 'Your word,' + word + ', comes after hello.'
... else:
...    print 'All right, hello.'
...
Your word, Pineapple, comes before hello.

A common way to address this problem is to convert strings to a standard format, such as all lowercase, before performing the comparison. Keep that in mind in case you have to defend yourself against a man armed with a Pineapple.

Nema komentara:

Objavi komentar