python - 如何让列表所有元素首字母变大写?
大家讲道理
大家讲道理 2017-04-17 17:50:28
0
5
1565

希望列表 c 所有元素首字母变大写,这样写为甚么会出错?该如何写?

c=['zz','yy','xx'] 
c[0:2]=c[0:2].capitalize()

# 提示错误
AttributeError: 'list' object has no attribute 'capitalize'
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

Antworte allen(5)
巴扎黑

capitalize 是字串的方法,而 c[0:2] 是一個 list,所以你調用 captitalize 的時候會出錯.

c = ['zz','yy','xx'] 
c = [string.capitalize() for string in c]

還有這樣也可以:

c = ['xx', 'yy', 'zz']
c = ' '.join(c).title().split()

P.S. 在使用 list 的時候,如果要操作的是整個串列,那不需要特別使用到切片,c[0:2] 在這裡是個不必要的做法.

給你參考!


@moling3650, 使用 title 真的是個有趣的主意,capitalize 只會將字串的首字大寫,而 title 則會將字串中所有的 單字 首字大寫。

見範例:

>>> string = 'my name is dokelung'
>>> string.capitalize()
'My name is dokelung'
>>> string.title()
'My Name Is Dokelung'

所以這樣也行:

>>> c = ['xx', 'yy', 'zz']
>>> ' '.join(c).title().split()
['Xx', 'Yy', 'Zz']
左手右手慢动作
[_.capitalize() for _ in c]
迷茫

写个不一样的

c = [_.title() for _ in c]
黄舟

list对象没有capitalize方法

巴扎黑

写个不一样的

map(str.title, c[0:2])
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!