search

Home  >  Q&A  >  body text

python - 如何让列表所有元素首字母变大写?

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

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

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

reply all(5)I'll reply

  • 巴扎黑

    巴扎黑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!


    @moling3650, Using 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

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 17:52:28

    [_.capitalize() for _ in c]

    reply
    0
  • 迷茫

    迷茫2017-04-17 17:52:28

    Write something different

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

    reply
    0
  • 黄舟

    黄舟2017-04-17 17:52:28

    The list object has no capitalize method

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 17:52:28

    Write something different

    map(str.title, c[0:2])

    reply
    0
  • Cancelreply