开发者

How do I generate a random string (of length X, a-z only) in Python? [duplicate]

开发者 https://www.devze.com 2022-12-14 23:07 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: python random string generation with upper case letter开发者_运维知识库s and digits
This question already has answers here: Closed 10 years ago.

Possible Duplicate:

python random string generation with upper case letter开发者_运维知识库s 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))


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消