0

您好,我正在尝试删除字符“+”

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

1 回答 1

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

你有一些语法问题,if else 必须在迭代之前。

于 2018-08-04T09:58:24.193 回答