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))
4
  • 3
    Nice use of generator expressions. But while we're saving memory, might as well use xrange instead of range.
    – Zach B
    Commented Dec 24, 2009 at 8:10
  • 4
    CytokineStorm, as of Python 3.x, range() behaves the same as xrange(). Commented Dec 24, 2009 at 9:28
  • Just keep in mind that any sequence generated by the random module is not cryptographically secure.
    – Federico
    Commented Jun 23, 2013 at 21:14
  • @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.). Commented Oct 17, 2016 at 14:29
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
  • 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". Commented Dec 24, 2009 at 10:39
  • Neither of these code samples implies uniqueness. Here is a test: pastie.org/8619409 Commented Jan 10, 2014 at 4:12
  • @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. Commented Oct 18, 2016 at 11:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.