I have a list of strings in Python, in which some of the strings start with character -
, and I want to remove such character.
I tried this sentence:
columns = [column[1:] for column in columns if column.startswith('-') else column]
but I get a Sintax Error
exception.
What is the right way to do this?
You want the result of the ternary operator to be the thing that goes in the list, so it all goes on the left:
columns = [column[1:] if column.startswith('-') else column for column in columns]
You can use an if
after the for .. in ...
to filter items out of the iteration completely, but else
has no meaning in that context, which is why you got a SyntaxError
.