How to: Generate random string in python

random string in python

Random string or random numbers are used most often by developers which can be used to create nonce , session keys , shorten the url , during authentication , encrypt the data etc etc. Lets see how can we generate random string in python using random.choice function

#!/usr/bin/python
import string
import random2
def getCode(length):

return ”.join(random2.choice(string.ascii_letters + string.digits + ‘-’ + ‘.’ + ‘_’ + ‘~’ ) for x in range(length))
# FUNCTION Call

print randgen(10)

If you see the above piece of code , we are importing string and random2 module . In python 3 random has been updated to random2 .using which we will call choice function.

In the above example we are generating random string which is UETF compliant which includes a-z , A-Z , 0-9 , -, . , ~ and _ characters.

Lets go through each line

#!/usr/bin/python
import string
import random2

In first line we are defining path for python , you must be knowing it if you know the basics of python. In the other next 2 lines we are importing string and random2 module ( Use random instead of random if python version < 3). Random2 module is used to call choice function responsible for generating random string . Module string is used to define ascii characters we will use in choice function.

def randgen(length):

return ”.join(random2.choice(string.ascii_letters + string.digits + ‘-’ + ‘.’ + ‘_’ + ‘~’ ) for x in range(length))

In the above piece of code we are defining a function randgen which we can later reuse in different line of code by calling it. we are returning random2.choice function output to it.

random2.choice function supports a single parameter which includes character which should be available in string separated by + symbol and returns only a single character. So we have defined a range for which it will interate through the given length.

To generate only random numbers we can use random2.choice function as below

random2.choice(string.digits)


four + 3 =

Top