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?
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?
''.join(random.choice(string.lowercase) for x in range(X))
range()
behaves the same as xrange()
.
Commented
Dec 24, 2009 at 9:28
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
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).
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
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