你好,我正在尝试删除字符'+'
>>> 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']
试试这个:
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必须在迭代之前出现。