24

Possible Duplicate:
python random string generation with upper case letters and digits

How do I generate a String of length X a-z in Python?

0

2 Answers 2

66
''.join(random.choice(string.lowercase) for x in range(X))
Sign up to request clarification or add additional context in comments.

4 Comments

Nice use of generator expressions. But while we're saving memory, might as well use xrange instead of range.
CytokineStorm, as of Python 3.x, range() behaves the same as xrange().
Just keep in mind that any sequence generated by the random module is not cryptographically secure.
@Federico: Unless you use random.SystemRandom(), which should be as cryptographically secure as the OS supports. In modules that need cryptographic randomness, I often do: import random, random = random.SystemRandom() to replace the module with an instance of the class that provides OS crypto-randomness. SystemRandom is the random.Random API, with randomness provided by os.urandom instead of Mersenne Twister (os.urandom is backed by stuff like Window's CryptGenRandom, UNIX-like /dev/urandom, etc.).
32

If you want no repetitions:

import string, random
''.join(random.sample(string.ascii_lowercase, X))

If you DO want (potential) repetitions:

import string, random
''.join(random.choice(string.ascii_lowercase) for _ in xrange(X)))

That's assuming that by a-z you mean "ASCII lowercase characters", otherwise your alphabet might be expressed differently in these expression (e.g., string.lowercase for "locale dependent lowercase letters" that may include accented or otherwise decorated lowercase letters depending on your current locale).

3 Comments

FYI, string.lowercase is rarely more than ASCII however you set the locale in my experience. I'm just noting that there is no true variable for "current alphabet".
Neither of these code samples implies uniqueness. Here is a test: pastie.org/8619409
@Altaisoft: You're misunderstanding how sample works. It only draws any given character once, but it's not drawing in order. So abc and cba would be different outputs. Your test is only valid (would have expected huge numbers of overlaps) if you assume sample returns them in the same order they appeared in the original string, but since they can appear in any order, there are (26+7)! / 7! options; overlaps won't be common.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.