希望列表 c
所有元素首字母变大写,这样写为甚么会出错?该如何写?
c=['zz','yy','xx']
c[0:2]=c[0:2].capitalize()
# 提示错误
AttributeError: 'list' object has no attribute 'capitalize'
巴扎黑2017-04-17 17:52:28
capitalize
is a string method, and c[0:2]
is a list, so when you call capitalize
Something went wrong. 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'
You can also do this:
>>> c = ['xx', 'yy', 'zz']
>>> ' '.join(c).title().split()
['Xx', 'Yy', 'Zz']
P.S. When using list, if you want to operate the entire list, there is no need to use slicing. c[0:2]
is unnecessary here. For your reference!
title
is really an interesting idea. capitalize
will only capitalize the first word of the string, while title
The first character of all #🎜🎜# words #🎜🎜# in the string will be capitalized. #🎜🎜#
#🎜🎜# See example: #🎜🎜#
rrreee
#🎜🎜#So this is okay: #🎜🎜#
rrreee