我有一个包含字符串的Python列表变量。是否有一个函数,可以转换所有的字符串在一个传递小写,反之亦然,大写?
当前回答
一个学生问,另一个有同样问题的学生回答:)
fruits=['orange', 'grape', 'kiwi', 'apple', 'mango', 'fig', 'lemon']
newList = []
for fruit in fruits:
newList.append(fruit.upper())
print(newList)
其他回答
如果你试图将列表中的所有字符串转换为小写,你可以使用pandas:
import pandas as pd
data = ['Study', 'Insights']
pd_d = list(pd.Series(data).str.lower())
输出:
['study', 'insights']
>>> list(map(str.lower,["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']
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)))
这可以通过列表推导来完成
>>> [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']
推荐文章
- 如何禁用标准错误流的日志记录?
- 用Matplotlib在Python中绘制时间
- 类中的Python装饰器
- 在Python中锁定文件
- 得到熊猫栏目的总数
- 从pandas DataFrame中删除名称包含特定字符串的列
- Mock vs MagicMock
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- 如何在matplotlib更新一个情节
- 不区分大小写列表搜索
- TypeError: ` NoneType `对象在Python中不可迭代
- 如何在Vim注释掉一个Python代码块