Note that there are some explanatory texts on larger screens.

plurals
  1. POBinary string in Python issues
    primarykey
    data
    text
    <p>For some reason I'm having a heck of a time figuring out how to do this in Python. I am trying to represent a binary string in a string variable, and all I want it to have is</p> <pre><code>0010111010 </code></pre> <p>However, no matter how I try to format it as a string, Python always chops off the leading zeroes, which is giving me a headache in trying to parse it out.</p> <p>I'd hoped <a href="https://stackoverflow.com/questions/733454/best-way-to-format-integer-as-string-with-leading-zeros">this question</a> would have helped, but it doesn't really...</p> <p>Is there a way to force Python to stop auto-converting my string to an integer?</p> <p>I have tried the following:</p> <pre><code>val = "" if (random.random() &gt; 0.50): val = val + "1" else val = val + "0" </code></pre> <p>and</p> <pre><code>val = "" if (random.random() &gt; 0.50): val = val + "%d" % (1) else: val = val + "%d" % (0) </code></pre> <p>I had stuck it into an array previously, but ran into issues inserting that array into another array, so I figured it would just be easier to parse it as a string. </p> <p>Any thoughts on how to get my leading zeroes back? The string is supposed to be a fixed length of 10 bits if that helps.</p> <hr> <p>Edit:</p> <p>The code:</p> <pre><code> def create_string(x): for i in xrange(10): # 10 random populations for j in xrange(int(x)): # population size v = ''.join(choice(('0','1')) for _ in range(10)) arr[i][j] = v return arr a = create_string(5) print a </code></pre> <p>Hopefully the output I'm seeing will show you why I'm having issues:</p> <pre><code>[[ 10000100 1100000001 101010110 111011 11010111] [1001111000 1011011100 1110110111 111011001 10101000] [ 110010001 1011010111 1100111000 1011100011 1000100001] [ 10011010 1000011001 1111111010 11100110 110010101] [1101010000 1010110101 110011000 1100001001 1010100011] [ 10001010 1100000001 1110010000 10110000 11011010] [ 111011 1000111010 1100101 1101110001 110110000] [ 110100100 1100000000 1010101001 11010000 1000011011] [1110101110 1100010101 1110001110 10011111 101101100] [ 11100010 1111001010 100011101 1101010 1110001011]] </code></pre> <p>The issue here isn't only with printing, I also need to be able to manipulate them on a per-element basis. So if I go to play with the first element, then it returns a 1, not a 0 (on the first element).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload