Search code examples
pythonjoinbit

Python : Generate a string of bits


I am trying to generate a random string of bits using the following code.

bitString = []

for i in range(0, 8):
    x = str(random.randint(0, 1))
    bitString.append(x)
    ''.join(bitString)

However instead of giving me something like this:

10011110

I get something that looks like this:

['1','0','0','1','1','1','1','0']

Can anyone point me in the direction of what I'm doing wrong?


Solution

  • Fixing your code:

    bitList = []
    
    for i in range(0, 8):
        x = str(random.randint(0, 1))
        bitList.append(x)
    
    bitString = ''.join(bitList)
    

    But more Pythonic would be this:

    >>> from random import choice
    >>> ''.join(choice('01') for _ in range(10))
    '0011010100'