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


当前回答

解决方案:

>>> s = []
>>> p = ['This', 'That', 'There', 'is', 'apple']
>>> [s.append(i.lower()) if not i.islower() else s.append(i) for i in p]
>>> s
>>> ['this', 'that', 'there', 'is','apple']

此解决方案将创建一个单独的列表,其中包含小写项,而不管它们的原始大小写。如果原始的大小写是大写,那么列表s将包含列表p中相应项的小写。如果列表p中列表项的原始大小写已经是小写,那么列表s将保留该项的大小写并保持其小写。现在你可以用列表s代替列表p。

其他回答

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

import pandas as pd

data = ['Study', 'Insights']

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

输出:

['study', 'insights']

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

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

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

使用val中的值列表:

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

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

一个学生问,另一个有同样问题的学生回答:)

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