This is what my problem is: I need to make a random string 50 characters long, made up of 1s and 0s.
I know how to solve this problem, and even have a one-liner for it. I have also looked for various solutions to this problem on SO, only to get back what I already know(1, 2, etc). But what I really want is the most Pythonic way of doing this.
Currently, I’m leaning towards ''.join(( random.choice([0,1]) for i in xrange(50) ))
Is there a more pythonic way of doing this? Is there a built-in that does something like this, perhaps in itertools?
For Python2.7 or better:
(In Python2.6, use
'{0:050b}'instead of'{:050b}'.)Explanation:
The
string.formatmethod can convert integers into their binary string representations. The basic format code to do this is'{:b}':To make a string of width 50, use the format code
'{:50b}':and to fill in the whitespace with zeros, use
{:050b}:The syntax for str.format is a bit daunting at first.
Here is my cheat sheet: