title: Random strings in Python 2.6 (Is this OK?)
body: <p>I've been trying to find a more pythonic way of generating random string in python that can scale as well. Typically, I see something similar to</p>
  
  <pre><code>''.join(random.choice(string.letters) for i in xrange(len))
  </code></pre>
  
  <p>It sucks if you want to generate long string.</p>
  
  <p>I've been thinking about random.getrandombits for a while, and figuring out how to convert that to an array of bits, then hex encode that. Using python 2.6 I came across the bitarray object, which isn't documented.  Somehow I got it to work, and it seems really fast.</p>
  
  <p>It generates a 50mil random string on my notebook in just about 3 seconds.</p>
  
  <pre><code>def rand1(leng):
      nbits = leng * 6 + 1
      bits = random.getrandbits(nbits)
      uc = u"%0x" % bits
      newlen = int(len(uc) / 2) * 2 # we have to make the string an even length
      ba = bytearray.fromhex(uc[:newlen])
      return base64.urlsafe_b64encode(str(ba))[:leng]
  </code></pre>
  
  <hr>
  
  <p><strong>edit</strong></p>
  
  <p>heikogerlach pointed out that it was an odd number of characters causing the issue. New code added to make sure it always sent fromhex an even number of hex digits.</p>
  
  <p>Still curious if there's a better way of doing this that's just as fast.</p>