如果以(字符)结尾的字符串如何删除列表中的字符串?

时间:2018-08-04 09:51:48

标签: python-3.x list-comprehension ends-with

你好,我正在尝试删除字符'+'

>>> a = ['eggs+', 'I don't want to remove this ', 'foo', 'spam+', 'bar+']
>>> a = [i[:-1] for i in a if i.ends with('+')]
>>> a
    ['eggs', 'spam', 'bar']
>>>

为什么是“我不想删除它”之类的原因 删除,如何删除“ +” 并留下其他所有东西

>>>['eggs', 'I don't want to remove this ', 'foo', 'spam', 'bar']

1 个答案:

答案 0 :(得分:2)

尝试一下:

a = ['eggs+', 'I dont want to remove this ', 'foo', 'spam+', 'bar+']
a = [i[:-1] if i.endswith('+') else i for i in a]
a

['eggs', 'I dont want to remove this ', 'foo', 'spam', 'bar']

您遇到了一些语法问题,如果不能,则必须在迭代之前出现。