I l@ve RuBoard Previous Section Next Section

3.9 Controlling Case

Credit: Luther Blissett

3.9.1 Problem

You need to convert a string from uppercase to lowercase, or vice versa.

3.9.2 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

3.9.3 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 a string s only if s starts with an uppercase letter, followed by at least one more character, including at least one more letter somewhere, and all letters except the first one are lowercase. Here's an alternative whose semantics may be easier to understand:

def iscapitalized(s):
    return s == s.capitalize(  )

However, this version deviates from the boundary-case semantics of the methods by accepting strings that are empty or contain no letters. Depending on your exact needs for boundary cases, you may of course implement precisely those checks you want to perform.

3.9.4 See Also

The Library Reference section on string methods; Perl Cookbook Recipe 1.9.

    I l@ve RuBoard Previous Section Next Section