Question

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?

Était-ce utile?

La 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'

Autres conseils

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

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

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)

My one-liner would be:

>>> import random
>>> print ''.join(random.choice("01") for i in range(8))
11100000
>>> 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top