Generate random strings of fixed length from given characters with equal occurance
<p>I want to generate random strings from a list of characters C (e.g. C = ['A', 'B', 'C', 'D']). This random string shall have length N (e.g. N = 32). Every character should occur equally often - in that example 8 times.</p>

<p>How can I implement that each character occurs equally often in here:</p>

<pre><code>''.join(random.choice(C) for i in range(N))
</code></pre>

<p>Or is there a better way?</p>

<p>I don't think you can guarantee that each item is picked with the same frequency if you use <code>random.choice</code>.  Each choice is equally likely which isn't the same thing.</p>

<p>The best way to do this would be to maintain a list of characters and shuffle it...</p>

<pre><code>characters = C * 8
random.shuffle(characters)
print(''.join(characters))
</code></pre>

<p>Or, if you want a bunch of them:</p>

<pre><code>def get_random_strings(characters, count, N):
    """Yield `N` strings that contain each character in `characters` `count` times."""
    characters = list(characters) * count
    for _ in xrange(N):
        random.shuffle(characters)
        yield ''.join(characters)
</code></pre>

python random fixed