how to edit each member of a list in python

后端 未结 2 1870
难免孤独
难免孤独 2021-01-28 04:20

I am new to python and I am trying to create a capitalize function that either capitalizes all words in a string or only the first word. Here is my function

def          


        
2条回答
  •  天命终不由人
    2021-01-28 04:36

    The bread-and-butter way to do this is to use a list comprehension:

    >>> l = ['one', 'two', 'three']
    >>> [w.capitalize() for w in l]
    ['One', 'Two', 'Three']
    

    This creates a copy of the list, with the expression applied to each of the items.

    If you don't want to create a copy, you could do this...

    >>> for i, w in enumerate(l):
    ...     l[i] = w.capitalize()
    ... 
    >>> l
    ['One', 'Two', 'Three']
    

    ...or this:

    l[:] = (w.capitalize() for w in l)
    

    The latter is probably the most elegant way to alter the list in-place, but note that it uses more temporary storage then the enumerate method.

提交回复
热议问题