compie
compie

Reputation: 10536

convert a list of booleans to string

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.

Upvotes: 5

Views: 2018

Answers (5)

jfs
jfs

Reputation: 414675

Here's generalized solution based on numpy.where():

#!/usr/bin/env python
import string, itertools

def where(selectors, x, y):
    return (xx if s else yy for xx, yy, s in itertools.izip(x, y, selectors))

condition = [True, True, False, True, True, False, True]
print ''.join(where(condition, string.uppercase, itertools.cycle(' ')))
# -> AB DE G

import numpy as np
print ''.join(np.where(condition, list(string.uppercase)[:len(condition)], ' '))
# -> AB DE G

Upvotes: 0

miles82
miles82

Reputation: 6804

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'

Upvotes: 8

Gary Kerr
Gary Kerr

Reputation: 14440

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))

Upvotes: 11

Amber
Amber

Reputation: 527183

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))

Upvotes: 1

Michał Marczyk
Michał Marczyk

Reputation: 84351

In [1]: ''.join(map(lambda b, c: c if b else ' ',
                    [True, True, False, True, True, False, True],
                    'ABCDEFG'))
Out[1]: 'AB DE G'

Upvotes: 2

Related Questions