Converting a String to Upper- or Lowercase
You want to convert all the characters in a string to upper- or lowercase letters.
Use the upper or lower function as appropriate.
For example, to convert aBcDe to uppercase, you would use:
>>> “aBcDe”.upper() ‘ABCDE’ >>> |
To convert it to lowercase, you would use:
>>> “aBcDe”.lower() ‘abcde’ >>> |
Discussion
In common with most functions that manipulate a string in some way, upper and lower do not actually modify the string, but rather return a modified copy of the string.
For example, the following code returns a copy of the string s, but note how the original string is unchanged.
>>> s = “aBcDe” >>> s.upper() ‘ABCDE’ >>> s ‘aBcDe’ >>> |
If you want to change the value of s to be all uppercase, then you need to do the following:
>>> s = “aBcDe” >>> s = s.upper() >>> s ‘ABCDE’ >>> |
See Also
See Recipe 5.16 for replacing text within strings.