How do you randomize a string in python?

Here is a helper that uses random to non-destructively shuffle, string, list or tuple:

def shuffle_any(o):
    is_l=is_t=False
    if isinstance(o, str):
        l = list(o)
    elif isinstance(o, list):
        l = o[:]
        is_l = True
    elif isinstance(o, tuple):
        is_t = True
        l = list(o)
    else:
        raise Exception("o is None!" if o is None \
                else f"Unexpected type: {o.__class__.__name__}")
    random.shuffle(l)
    return l if is_l else tuple(l) if is_t else ''.join(l)

Usage:

print(f"shuffle_any('abcdefg'): {shuffle_any('abcdefg')}")
print(f"shuffle_any([1,2,3,4,5]): {shuffle_any([1,2,3,4,5])}")
print(f"shuffle_any((1,2,3,4,5)): {shuffle_any((1,2,3,4,5))}")

Output:

shuffle_any('abcdefg'): dfceabg
shuffle_any([1,2,3,4,5]): [5, 2, 3, 4, 1]
shuffle_any((1,2,3,4,5)): (4, 3, 2, 5, 1)

next → ← prev

A random refers to the collection of data or information that can be available in any order. The random module in python is used to generate random strings. The random string is consisting of numbers, characters and punctuation series that can contain any pattern. The random module contains two methods random.choice() and secrets.choice(), to generate a secure string. Let's understand how to generate a random string using the random.choice() and secrets.choice() method in python.

How do you randomize a string in python?

Using random.choice()

The random.choice() function is used in the python string to generate the sequence of characters and digits that can repeat the string in any order.

Create a program to generate a random string using the random.choices() function.

Random_str.py

Output:

How do you randomize a string in python?

Following are the method used in the random module to generate the random string.

MethodsDescription
String.ascii_letters It returns a random string that contains both uppercase and lowercase characters.
String_ascii_uppercase It is a random string method that only returns a string in uppercase characters.
String.ascii_lowercase It is a random string method that returns a string only in lowercase characters.
String.digits It is a random string method that returns a string with numeric characters.
String.punctuation It is a random string method that returns a string with punctuation characters.

Generate a random string of upper case and lower-case letters

UprLwr.py

Output:

How do you randomize a string in python?

Random String of Specified Characters

Specific.py

Output:

How do you randomize a string in python?

Note: The random.choice() method is used in the python program to repeat the same characters strings. If we don't want to display repetitive characters, we should use random.sample() function.

Generate a random string without repeating the same characters

WithoutRepeat.py

Output:

How do you randomize a string in python?

As we can see in the above output, the random.sample() method returns a string in which all characters are unique and non-repeating. Whereas, the random.choice() method returns a string that may contain repetitive characters. So, we can say that if we want to generate a unique random string, use random.sample() method.

Generate a random alphanumeric string consisting of fixed letters and digits

For example, suppose we want a randomly generated alphanumeric string that contains five letters and four digits. We need to define these parameters into the function.

Let's write a program to generate an alphanumeric string that contains a fixed number of letters and digits.

fixedString.py

Output:

How do you randomize a string in python?

Using secrets.choice()

A secrets.choice() method is used to generate a more secure random string than random.choice(). It is a cryptographically random string generator that ensures no two processes can obtain the same results simultaneously using secrets.choice() method.

Let's write a program to print a secure random string using the secrets.choice method.

Secret_str.py

Output:

How do you randomize a string in python?

Use the different method of the random module to generate a safe random string.

Let's write a program to print secure random strings using different methods of secrets.choice().

Secret.py

Output:

How do you randomize a string in python?

Next TopicYield Keyword in Python

← prev next →

How do you jumble a string in Python?

In this, we need to disintegrate string into character list, scramble using sample(), rejoin them using join() and then remake list using list comprehension. This is similar to the above method. The only difference is that shuffle() is used to perform scramble task than using sample().

How do you randomize data in Python?

Python Random shuffle() Method The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.

How do you create a random string list in Python?

Random_str.py.
import string..
import random # define the random module..
S = 10 # number of characters in the string..
# call random. ... .
ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k = S)).
print("The randomly generated string is : " + str(ran)) # print the random data..

How do you randomize two strings in Python?

How to Create a Random String in Python.
Import string and random module. ... .
Use the string constant ascii_lowercase. ... .
Decide the length of a string. ... .
Use a for loop and random choice() function to choose characters from a source. ... .
Generate a random Password..