Slice every string in list in Python

前端 未结 3 1418
别那么骄傲
别那么骄傲 2020-12-22 03:38

I want to slice every string in a list in Python.

This is my current list:

[\'One\', \'Two\', \'Three\', \'Four\', \'Five\']

This i

相关标签:
3条回答
  • 2020-12-22 04:20

    You can do:

    >>> l = ['One', 'Two', 'Three', 'Four', 'Five'] 
    >>> [i[:-2] for i in l]
    ['O', 'T', 'Thr', 'Fo', 'Fi']
    
    0 讨论(0)
  • 2020-12-22 04:34
    x=['One', 'Two', 'Three', 'Four', 'Five']
    print map(lambda i:i[:-2],x)  #for python 2.7
    print list(map(lambda i:i[:-2],x)) #for python 3
    
    0 讨论(0)
  • 2020-12-22 04:40

    Use a list comprehension to create a new list with the result of an expression applied to each element in the inputlist; here the [:-2] slices of the last two characters, returning the remainder:

    [w[:-2] for w in list_of_words]
    

    Demo:

    >>> list_of_words = ['One', 'Two', 'Three', 'Four', 'Five']
    >>> [w[:-2] for w in list_of_words]
    ['O', 'T', 'Thr', 'Fo', 'Fi']
    
    0 讨论(0)
提交回复
热议问题