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?

Community
  • 1
  • 1
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

2 Answers2

65
''.join(random.choice(string.lowercase) for x in range(X))
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 3
    Nice use of generator expressions. But while we're saving memory, might as well use xrange instead of range. – Zach B Dec 24 '09 at 08:10
  • 4
    CytokineStorm, as of Python 3.x, `range()` behaves the same as `xrange()`. – Evan Fosmark Dec 24 '09 at 09:28
  • Just keep in mind that any sequence generated by the random module is *not* cryptographically secure. – Federico Jun 23 '13 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.). – ShadowRanger Oct 17 '16 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).

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 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". – u0b34a0f6ae Dec 24 '09 at 10:39
  • Neither of these code samples implies uniqueness. Here is a test: http://pastie.org/8619409 – Anatoly Scherbakov Jan 10 '14 at 04: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. – ShadowRanger Oct 18 '16 at 11:27