首页 > 解决方案 > 拆分然后删除理解中的最后一个字符

问题描述

我正在尝试在 python 中编写一个理解来拆分字符串,然后删除结果列表中每个元素中的最后一个字符,例如:

>>> text = "firstX secondY thirdZ"
>>> split_text = < some code >
>>> print(split_text)
['first','second','third']

我可以让它做我想做的事而无需理解:

>>> text = "firstX secondY thirdZ"
>>> split_text = []
>>> for temp in text.split():
...     split_text.append(temp[:-1])
... 
>>> print(split_text)
['first', 'second', 'third']

但我想学习如何在一个单一的理解中做到这一点..

标签: pythonlist-comprehension

解决方案


试试下面

text = "firstX secondY thirdZ"
text_lst = [x[:-1] for x in text.split(' ')]
print(text_lst)

输出

['first', 'second', 'third']

推荐阅读