我有一个包含字符串的Python列表变量。是否有一个函数,可以转换所有的字符串在一个传递小写,反之亦然,大写?
当前回答
这可以通过列表推导来完成
>>> [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']
其他回答
>>> list(map(str.lower,["A","B","C"]))
['a', 'b', 'c']
mylist = ['Mixed Case One', 'Mixed Case Two', 'Mixed Three']
print(list(map(lambda x: x.lower(), mylist)))
print(list(map(lambda x: x.upper(), mylist)))
对于这个例子,理解是最快的
$ 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
如果你试图将列表中的所有字符串转换为小写,你可以使用pandas:
import pandas as pd
data = ['Study', 'Insights']
pd_d = list(pd.Series(data).str.lower())
输出:
['study', 'insights']
如果你的目的是通过一次转换来匹配另一个字符串,你也可以使用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
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录