How do I convert this:
[True, True, False, True, True, False, True]
Into this:
'AB DE G'
Note: C and F are missing in the output because the corresponding items in the input list are False.
Assuming your list of booleans is not too long:
bools = [True, True, False, True, True, False, True]
print ''.join(chr(ord('A') + i) if b else ' ' for i, b in enumerate(bools))
You can use string.uppercase instead of chr/ord. This will give you locale-dependent results. For ascii you can use string.ascii_uppercase.
>>> import string
>>> bools = [True, True, False, True, True, False, True]
>>> ''.join(string.uppercase[i] if b else ' ' for i, b in enumerate(bools))
'AB DE G'
In [1]: ''.join(map(lambda b, c: c if b else ' ',
[True, True, False, True, True, False, True],
'ABCDEFG'))
Out[1]: 'AB DE G'
inputs = [True, True, False, True, True, False, True]
outputs = []
for i,b in enumerate(inputs):
if b:
outputs.append(chr(65+i)) # 65 = ord('A')
else:
outputs.append(' ')
outputstring = ''.join(outputs)
or the list comprehension version
inputs = [True, True, False, True, True, False, True]
outputstring = ''.join(chr(65+i) if b else ' ' for i,b in enumerate(inputs))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With