我有一个包含字符串的Python列表变量。是否有一个函数,可以转换所有的字符串在一个传递小写,反之亦然,大写?


当前回答

如果你的目的是通过一次转换来匹配另一个字符串,你也可以使用str.casefold()。

这是有用的,当你有非ascii字符和匹配ascii版本(例如:maße vs masse)。虽然str.lower或str.upper在这种情况下失败,但str.casefold()将通过。 这在Python 3中可用,详细讨论了这个想法,答案是https://stackoverflow.com/a/31599276/4848659。

>>>str="Hello World";
>>>print(str.lower());
hello world
>>>print(str.upper());
HELLO WOLRD
>>>print(str.casefold());
hello world

其他回答

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

上面的答案由@Amorpheuses给出了一个更简单的版本。

使用val中的值列表:

valsLower = [item.lower() for item in vals]

使用f = open()文本源,这对我来说工作得很好。

如果你试图将列表中的所有字符串转换为小写,你可以使用pandas:

import pandas as pd

data = ['Study', 'Insights']

pd_d = list(pd.Series(data).str.lower())

输出:

['study', 'insights']

对于这个例子,理解是最快的

$ 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

除了更容易阅读(对许多人来说),列表推导式也在速度竞赛中获胜:

$ 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