Reputation: 35
I am trying to generate random number in python using random.sample . This is how I am writing code .
import random
r = "".join(random.sample("abcdefghijklmnopqrstuvwxyz", 10))
Above code generates random numbers of length 10 whose letters are populated from the letters a-z. How can i use regular expressions over there like [a-z]?
Upvotes: 2
Views: 251
Reputation: 63747
If you have the pyparsing module handy, you can use the srange method to expand a regex character set to a string of characters:
>>> from pyparsing import srange
>>> srange('[a-z]')
u'abcdefghijklmnopqrstuvwxyz'
>>> srange('[a-z0-9]')
u'abcdefghijklmnopqrstuvwxyz0123456789'
Upvotes: 1
Reputation: 133634
Just use this instead
>>> from string import ascii_lowercase, ascii_uppercase
>>> ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
If you want to generate digits you can use range
>>> map(str, range(10))
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
Upvotes: 4