Recipe1.12.Controlling Case


Recipe 1.12. 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( )

Characters that are not letters are copied unchanged.

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 again similar, but it capitalizes the first letter of each word (where a "word" is a sequence of letters) and uses lowercase for all other letters:

>>> 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 whether a string object is already in a given case form, with the methods isupper, islower, and istitle, which all return true if the string is not empty, contains at least one letter, and already meets the uppercase, lowercase, or titlecase constraints. There is no analogous iscapitalized method, and coding it is not trivial, if we want behavior that's strictly similar to strings' is... methods. Those methods all return False for an "empty" string, and the three case-checking ones also return False for strings that, while not empty, contain no letters at all.

The simplest and clearest way to code iscapitalized is clearly:

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

However, this version deviates from the boundary-case semantics of the analogous is... methods, since it also returns TRue for strings that are empty or contain no letters. Here's a stricter one:

import string notrans = string.maketrans('', '')  # identity "translation" def containsAny(str, strset):     return len(strset) != len(strset.translate(notrans, str)) def iscapitalized(s):     return s == s.capitalize( ) and containsAny(s, string.letters)

Here, we use the function shown in Recipe 1.8 to ensure we return False if s is empty or contains no letters. As noted in Recipe 1.8, this means that this specific version works only for plain strings, not for Unicode ones.

See Also

Library Reference and Python in a Nutshell docs on string methods; Perl Cookbook recipe 1.9; Recipe 1.8.



Python Cookbook
Python Cookbook
ISBN: 0596007973
EAN: 2147483647
Year: 2004
Pages: 420

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net