我希望在Python中对列表中的每个字符串进行切片。
这是我的当前列表:
['One', 'Two', 'Three', 'Four', 'Five']
这是我期望的结果列表:
['O', 'T', 'Thr', 'Fo', 'Fi']
我想从我的列表中的每个字符串中切掉最后两个字符。
我该怎么做?
我希望在Python中对列表中的每个字符串进行切片。
这是我的当前列表:
['One', 'Two', 'Three', 'Four', 'Five']
这是我期望的结果列表:
['O', 'T', 'Thr', 'Fo', 'Fi']
[:-2]
切片,返回余数。[w[:-2] for w in list_of_words]
>>> list_of_words = ['One', 'Two', 'Three', 'Four', 'Five']
>>> [w[:-2] for w in list_of_words]
['O', 'T', 'Thr', 'Fo', 'Fi']
您可以做以下事情:
>>> l = ['One', 'Two', 'Three', 'Four', 'Five']
>>> [i[:-2] for i in l]
['O', 'T', 'Thr', 'Fo', 'Fi']
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