I have a Python list variable that contains strings. Is there a function that can convert all the strings in one pass to lowercase and vice versa, uppercase?
Simply use the Python string lower() method to convert every element in a list of strings into lowercase. It will convert given into lowercase letters in Python.
Uppercase. To turn a string to uppercase in Python, use the built-in upper() method of a string. To turn a list of strings to uppercase, loop through the list and convert each string to upper case.
Use string upper() method to convert every element in a list of strings into uppercase (capitalize) in Python code.
Use the string lower() method to convert every element in a list of strings into lowercase in Python. Python list variable that contains strings needed to iterate through the loop and add back lowercase value into a list.
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 the map
function
>>> list(map(lambda x: x.lower(), ["A", "B", "C"])) ['a', 'b', 'c'] >>> list(map(lambda x: x.upper(), ["a", "b", "c"])) ['A', 'B', 'C']
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With