3

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?

5 Answers 5

4

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'
Sign up to request clarification or add additional context in comments.

Comments

4

You are joining the results in the loop itself. You can unindent the join line, like this

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

Or, better, you can use generator expression like this

print "".join(str(random.randint(0, 1)) for i in range(8))

Comments

0

You could declare bitString as string variable (instead of appending to list and then converting to string):

bitString = ""
for i in range(0, 8):
    x = str(random.randint(0, 1))
    bitString += x

print bitString

Comments

0

Your code is right, but misses 3 "words": import, random and print)

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

Comments

0

My one-liner would be:

>>> import random
>>> print ''.join(random.choice("01") for i in range(8))
11100000
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.