使列表中的字符串大写 - Python 3

Log*_*gan 4 python-3.x uppercase

我正在学习python,并通过一个实际示例遇到了一个我似乎无法找到解决方案的问题。我使用以下代码得到的错误是 'list' object has to attribute 'upper'.

def to_upper(oldList):
    newList = []
    newList.append(oldList.upper())

words = ['stone', 'cloud', 'dream', 'sky']
words2 = (to_upper(words))
print (words2)
Run Code Online (Sandbox Code Playgroud)

ara*_*oid 5

由于该upper()方法仅针对字符串而不是针对列表定义,因此您应该遍历列表并将列表中的每个字符串大写,如下所示:

def to_upper(oldList):
    newList = []
    for element in oldList:
        newList.append(element.upper())
    return newList
Run Code Online (Sandbox Code Playgroud)

这将解决您的代码问题,但是如果您想大写字符串数组,则有更短/更紧凑的版本。

  • 地图功能map(f, iterable)。在这种情况下,您的代码将如下所示:

    words = ['stone', 'cloud', 'dream', 'sky']
    words2 = list(map(str.upper, words))
    print (words2)
    
    Run Code Online (Sandbox Code Playgroud)
  • 列表理解 [func(i) for i in iterable]。在这种情况下,您的代码将如下所示:

    words = ['stone', 'cloud', 'dream', 'sky']
    words2 = [w.upper() for w in words]
    print (words2)
    
    Run Code Online (Sandbox Code Playgroud)