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