简体   繁体   English

在 Python 中对列表中的每个字符串进行切片

[英]Slice every string in list in Python

I want to slice every string in a list in Python.我想在 Python 中对列表中的每个字符串进行切片。

This is my current list:这是我目前的清单:

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

This is the list I want for result:这是我想要的结果列表:

['O', 'T', 'Thr', 'Fo', 'Fi']

I want to slice away the two last characters from every single string in my list.我想从列表中的每个字符串中切掉最后两个字符。

How can I do this?我怎样才能做到这一点?

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:这里是最后两个字符的[:-2]切片,返回余数:

[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']

You can do:你可以做:

>>> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM