Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 879
TIMEX Avatar asked Dec 24 '09 07:12

TIMEX


People also ask

How do you create a string length of N in Python?

Other ways to "make a string of 10 characters": 'x'*10 (all the ten characters will be lowercase x s;-), ''. join(chr(ord('a')+i) for i in xrange(10)) (the first ten lowercase letters again), etc, etc;-). In Python 3.1. 1, it's string.


2 Answers

''.join(random.choice(string.lowercase) for x in range(X)) 
like image 103
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 12:09

Ignacio Vazquez-Abrams


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

like image 26
Alex Martelli Avatar answered Sep 28 '22 10:09

Alex Martelli