ThatOneGuyInXNA
ThatOneGuyInXNA

Reputation: 111

String to list of certain characters

So I am working in Python and I would like to turn a string into a list of characters

VALID_SYMBOLS is a list of characters and EMPTY_SYMBOL is a dash.

I would like to loop over each element in symbols and if it is valid, keep it and if it is invalid then turn it into EMPTY_SYMBOL, but I am getting an error at the else:

symbols = list(line)
symbols = [x for x in symbols if any(x == y for y in VALID_SYMBOLS) else EMPTY_SYMBOL]

Is there a more Pythonic way to do this?

Upvotes: 0

Views: 76

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

The if and else come first:

symbols = [x if x in VALID_SYMBOLS else EMPTY_SYMBOL  for x in symbols ] 

EMPTY_SYMBOL will have to be defined somewhere.

Upvotes: 1

jonrsharpe
jonrsharpe

Reputation: 121976

You have the list comprehension around the wrong way:

symbols = [x if x in VALID_SYMBOLS else EMPTY_SYMBOL for x in symbols]

(Note also the logic simplification.)

The if after for foo in bar is for filtering, and is effectively else pass - this would skip over the invalid xs, not replace them with EMPTY_SYMBOL:

>>> [x for x in [1, 2, 3] if x % 2]
[1, 3]
>>> [x if x % 2 else 0 for x in [1, 2, 3]]
[1, 0, 3]

Upvotes: 1

Related Questions