Convert a Python list with strings all to lowercase or uppercase

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

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?

回答1:

It can be done with list comprehensions. These basically take the form of [function-of-item for item in some-list]. For example, to create a new list where all the items are lower-cased (or upper-cased in the second snippet), you would use:

>>> [x.lower() for x in ["A","B","C"]] ['a', 'b', 'c']  >>> [x.upper() for x in ["a","b","c"]] ['A', 'B', 'C'] 

You can also use the map function:

>>> map(lambda x:x.lower(),["A","B","C"]) ['a', 'b', 'c'] >>> map(lambda x:x.upper(),["a","b","c"]) ['A', 'B', 'C'] 


回答2:

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 


回答3:

>>> map(str.lower,["A","B","C"]) ['a', 'b', 'c'] 


回答4:

List comprehension is how I'd do it, it's the "Pythonic" way. The following transcript shows how to convert a list to all upper case then back to lower:

pax@paxbox7:~$ python3 Python 3.5.2 (default, Nov 17 2016, 17:05:23)  [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information.  >>> x = ["one", "two", "three"] ; x ['one', 'two', 'three']  >>> x = [element.upper() for element in x] ; x ['ONE', 'TWO', 'THREE']  >>> x = [element.lower() for element in x] ; x ['one', 'two', 'three'] 


回答5:

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 


回答6:

mylist = ['Mixed Case One', 'Mixed Case Two', 'Mixed Three'] print map(lambda x: x.lower(), mylist) print map(lambda x: x.upper(), mylist) 


回答7:

a student asking, another student with the same problem answering :))

fruits=['orange', 'grape', 'kiwi', 'apple', 'mango', 'fig', 'lemon'] newList = [] for fruit in fruits:     newList.append(fruit.upper()) print(newlist) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!