Controlling Case
Credit: Luther Blissett
Problem
You need to convert a string from uppercase to lowercase, or vice versa.
Solution
That’s what the
upper and
lower methods of string objects are for. Each
takes no arguments and returns a copy of the string in which each
letter has been changed to upper- or lowercase, respectively.
big = little.upper( ) little = big.lower( )
s.capitalize is similar to
s[:1].upper()+s[1:].lower( ). The first character
is changed to uppercase, and all others are changed to lowercase.
s.title is similar, but it uppercases the first
letter of each word:
>>> print 'one two three'.capitalize( ) One two three >>> print 'one two three'.title( ) One Two Three
Discussion
Case manipulation of strings is a very frequent need. Because of
this, several string methods let you produce case-altered copies of
strings. Moreover, you can also check if a string object is already
in a given case form with the methods isupper,
islower, and istitle, which all
return 1 if the string is nonempty and already
meets the uppercase, lowercase, or titlecase constraints. There is no
iscapitalized
method, but we can code it as a function:
def iscapitalized(s):
return s[:1].isupper() and s[1:].islower( )This may not be exactly what you want, because each of the
is methods returns 0 for an
empty string, and the three case-checking ones also return
0 for strings that, while not empty, contain no
letters at all. This iscapitalized function does not quite match these semantics; rather, it accepts ...