Here is the code I was trying to turn into a list comprehension:
table = ''
for index in xrange(256):
if index in ords_to_keep:
table += chr(index)
else:
table += replace_with
Is there a way to add the else statement to this comprehension?
table = ''.join(chr(index) for index in xrange(15) if index in ords_to_keep)
The syntax a if b else c
is a ternary operator in Python that evaluates to a
if the condition b
is true - otherwise, it evaluates to c
. It can be used in comprehension statements:
>>> [a if a else 2 for a in [0,1,0,3]]
[2, 1, 2, 3]
So for your example,
table = ''.join(chr(index) if index in ords_to_keep else replace_with
for index in xrange(15))