切片Python中列表中的每个字符串 [英] Slice every string in list in Python

查看:498
本文介绍了切片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.

我该怎么做?

推荐答案

使用

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中列表中的每个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆