大写字母并理解列表

时间:2018-09-15 19:04:51

标签: python python-3.x list-comprehension

names = ['one', 'two']
print([n[0].upper() for n in names])

我想要这样的输出:    一,二

如何使用python做到这一点?

2 个答案:

答案 0 :(得分:6)

>>> names = ['one', 'two']
>>> names = [n.title() for n in names]
>>> names
['One', 'Two']
>>> 

如果您希望它使用大写字母,例如oNe将是ONe,那么:

>>> names = ['oNe', 'twO']
>>> names = [n[0].upper()+n[1:] if n else "" for n in names]
>>> names
['ONe', 'TwO']
>>> 

答案 1 :(得分:1)

您需要使用Python标准库的'capitalize()'方法。代码如下:

names = ['one', 'two']
print([n.capitalize() for n in names])

因此,您将获得以下输出: ['One','Two']