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

新手上路,请多包涵

我正在学习 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)

原文由 Logan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 452
1 个回答

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

 def to_upper(oldList):
    newList = []
    for element in oldList:
        newList.append(element.upper())
    return newList

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

  • 映射 函数 map(f, iterable) 。在这种情况下,您的代码将如下所示:
   words = ['stone', 'cloud', 'dream', 'sky']
  words2 = list(map(str.upper, words))
  print (words2)

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

原文由 araknoid 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进