Last modified: Jan 10, 2023 By Alexander Williams

How to make a random string in python

How to make a random string

In this article, we are going to learn how to make a random string and how to set it.

Let see the Code :

1
2
3
4
5
6
7
8
import random
import string

def randomString(stringLength=10):

        """Generate a random string of fixed length """
        letters = string.ascii_lowercase
        return ''.join(random.choice(letters) for i in range(stringLength))

As you can see, this random function contains a value, and this value means string Length. So you can choose How many letters do you want to be returned.:

1
2
3
4
5
6
7
8
9
import random
import string

def randomString(stringLength=10):          
    """Generate a random string of fixed length """
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(stringLength))
               
 print ("Random String is ", randomString(20) )

Output:

1
Random String is  muluadwbxfexhsxeopmt 

hope this helps