chevron_left
275 points
10 4 4

A series of numbers and letters that have no specific pattern is considered as a Random String. It also known as Random Character String. Basically It used to generate a unique set of strings with the pupose of data testing. In Python, random module used to generate the random strings.

Generating a random string 

The random.choice() and secrets.choice() functions from random module used to generate a secure string. By using python string, The random.choice() function generate the sequence of characters and digits that can repeat the string in any order. There are some methods that commonly used to specify the type of generated string. Such as:

  • string.ascii_letters used for both uppercase and lowercase characters.
  • string._ascii_uppercase used for only a string in uppercase characters.
  • string._ascii_lowercase used for only a string in lowercase characters.
  • string.digits used for a string with numeric characters.
  • string.punctuation used for a string with punctuation characters.

Code example:

import random  
import string  
def Upper_Lower_string(length): 

    result = ''.join((random.choice(string.ascii_lowercase) for x in range(length))) 
    print(" Random string generated in Lowercase: ", result)  
  
    result1 = ''.join((random.choice(string.ascii_uppercase) for x in range(length)))   
    print(" Random string generated in Uppercase: ", result1)  
  
Upper_Lower_string(10)

Example output:

 Random string generated in Lowercase:  wnzzuhkeao
 Random string generated in Uppercase:  MNNSXFMOSR

It should be noted that, the random.choice() method may gives repetation of a single character for multiple times. To avoid repetation of same character, just use the random.sample() function.

1 Comment

Your  explanations  is very helpful and useful for me. Well post again thank you. Generate a random string in python is very important.

More Posts

How to make a random number generator in c++ Sanjana Sagar - May 20
Pseudo Random Number Generator (PRNG) in C ++ Sanjana Sagar - May 27
how to generate random numbers with a range in C++? Lalit Kumar - Apr 17, 2020
How to replace a character in a string in Python? Hafsa_Rao - Aug 16
Python how to count number of characters in a string NYM2602 - Aug 4
How to count the number of characters in a string python mhfaisal - Jun 30
How to reverse a string in python amna - Oct 20, 2020
How to generate random numbers in java within range Hasnain_khan - Oct 13, 2020
How to generate random numbers between 0 and 1 in C++( with explanation )? Lalit Kumar - Jun 23, 2020
How to generate random numbers between 0 and 1 in C++? Lalit Kumar - May 15, 2020