切片Python中列表中的每个字符串

切片Python中列表中的每个字符串

本文介绍了切片Python中列表中的每个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对Python列表中的每个字符串进行切片.

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

这是我当前的列表:

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

我该怎么做?

推荐答案

使用列表理解以创建一个新列表,并将表达式的结果应用于输入列表中的每个元素;这是最后两个字符的[:-2]切片,返回其余部分:

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]

演示:

>>> list_of_words = ['One', 'Two', 'Three', 'Four', 'Five']
>>> [w[:-2] for w in list_of_words]
['O', 'T', 'Thr', 'Fo', 'Fi']

这篇关于切片Python中列表中的每个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 05:23