Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list with strings all to lowercase or uppercase

Tags:

python

list

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?

like image 793
user219126 Avatar asked Nov 26 '09 05:11

user219126


People also ask

How do you convert a whole list to lowercase in Python?

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.

How can I uppercase all strings in a list?

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.

How do you make elements in a list uppercase?

Use string upper() method to convert every element in a list of strings into uppercase (capitalize) in Python code.

Can you use lower () on a list?

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.


2 Answers

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'] 
like image 88
YOU Avatar answered Oct 05 '22 07:10

YOU


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 
like image 34
Ned Deily Avatar answered Oct 05 '22 07:10

Ned Deily