title: hex to string formatting conversion in python
body: <p>I used to generate random string in the following way (now I've switched to <a href="https://stackoverflow.com/questions/785058/random-strings-in-python-2-6-is-this-ok/785086#785086" title="this method">this method</a>).</p>
  
  <pre><code>key = '%016x' % random.getrandbits(128)
  </code></pre>
  
  <p>The key generated this way is most often a 32 character string, but once I've got 31 chars.</p>
  
  <p>This is what I don't get: <strong>why it's 32 chars, not 16</strong>? Doesn't one hex digit take one character to print? </p>
  
  <p>So if I ask for <code>%016x</code> - shouldn't one expect sixteen chars with possible leading zeroes?</p>
  
  <p><strong>Why string legth is not always the same?</strong></p>
  
  <h1>Test case</h1>
  
  <pre><code>import random
  import collections
  stats = collections.defaultdict(int)
  for i in range(1000000):
      key = '%016x' % random.getrandbits(128)
      length = len(key)
      stats[length] += 1
  
  for key in stats:
      print key, ' ', stats[key]
  </code></pre>
  
  <p>Prints:</p>
  
  <pre><code>32   937911
  27   1
  28   9
  29   221
  30   3735
  31   58123
  </code></pre>