我有一个包含字符串的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

其他回答

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

$ 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

这可以通过列表推导来完成

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

或者使用映射函数

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

列表理解是我的做法,这是“python”的方式。下面的文字记录展示了如何将一个列表全部转换为大写,然后再转换回小写:

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']

如果你的目的是通过一次转换来匹配另一个字符串,你也可以使用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

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

使用val中的值列表:

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

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