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


当前回答

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)))

其他回答

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

你可以尝试使用:

my_list = ['india', 'america', 'china', 'korea']

def capitalize_list(item):
    return item.upper()

print(list(map(capitalize_list, my_list)))

解决方案:

>>> 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。

>>> 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)))