I have a python list variable that contains strings. Is there a python function that can convert all the strings in one pass to lowercase and vice versa, uppercase?
Regards
I have a python list variable that contains strings. Is there a python function that can convert all the strings in one pass to lowercase and vice versa, uppercase?
Regards
It can be done with list comprehensions
>>> [x.lower() for x in ["A","B","C"]]
['a', 'b', 'c']
>>> [x.upper() for x in ["a","b","c"]]
['A', 'B', 'C']
or with map function
>>> map(lambda x:x.lower(),["A","B","C"])
['a', 'b', 'c']
>>> map(lambda x:x.upper(),["a","b","c"])
['A', 'B', 'C']
List comprehensions is how I'd do it. This snippet below shows how to convert a list to all upper case then back to lower:
$ python
Python 2.5.2 (r252:60911, Dec 2 2008, 09:26:14)
[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> list = ["one", "two", "three"]
>>> list
['one', 'two', 'three']
>>> list = [element.upper() for element in list]
>>> list
['ONE', 'TWO', 'THREE']
>>> list = [element.lower() for element in list]
>>> list
['one', 'two', 'three']
mylist = ['Mixed Case One', 'Mixed Case Two', 'Mixed Three']
print map(lambda x: x.lower(), mylist)
print map(lambda x: x.upper(), mylist)
Besides being easier to read (for many people), list comprehensions win the speed race, too:
$ python2.6 -m timeit '[x.lower() for x in ["A","B","C"]]'
1000000 loops, best of 3: 1.03 usec per loop
$ python2.6 -m timeit '[x.upper() for x in ["a","b","c"]]'
1000000 loops, best of 3: 1.04 usec per loop
$ python2.6 -m timeit 'map(str.lower,["A","B","C"])'
1000000 loops, best of 3: 1.44 usec per loop
$ python2.6 -m timeit 'map(str.upper,["a","b","c"])'
1000000 loops, best of 3: 1.44 usec per loop
$ python2.6 -m timeit 'map(lambda x:x.lower(),["A","B","C"])'
1000000 loops, best of 3: 1.87 usec per loop
$ python2.6 -m timeit 'map(lambda x:x.upper(),["a","b","c"])'
1000000 loops, best of 3: 1.87 usec per loop
For this sample the comprehension is fastest
$ python -m timeit -s 's=["one","two","three"]*1000' '[x.upper for x in s]' 1000 loops, best of 3: 809 usec per loop $ python -m timeit -s 's=["one","two","three"]*1000' 'map(str.upper,s)' 1000 loops, best of 3: 1.12 msec per loop $ python -m timeit -s 's=["one","two","three"]*1000' 'map(lambda x:x.upper(),s)' 1000 loops, best of 3: 1.77 msec per loop
Depending on your inputstream there might be special cases to look for. One that I know of is German "ß" for which there is no uppercase letter. Its rendered to an "SS" in uppercase.