Search code examples
python-3.xlist-comprehensionends-with

How do I remove a character of strings in a list if it ends with (character)?


Hello I am trying to remove the Character '+'

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

why are "I don't want to remove this" and the like getting removed and how do I just remove the '+' and leave every thing else like

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

Solution

  • Try this:

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

    You had some syntax issues, the if else must come before the iteration.