Python is a flexible programming language that is used for many different things. One of its many built-in features includes a method that generates random strings. This is useful for a range of tasks like creating passwords and usernames. Today, we will learn how to create random strings in python, or simply, a python password generator.
But first, we need to understand the Random module. The Random module is a built-in library in a python module using which we can create random strings of digits and alphabets as per our requirement.
To use the random module, you first need to import it:
import random
How to Create Random Strings in Python?
Many functions that can be used to create random strings are included in the random module, including:
- random.choice(seq): This function returns a random element from the given sequence.
- random.choices(population, weights=None, *, cum_weights=None, k=1): This function returns a list of k elements from the population with replacement.
- random.sample(population, k): This function returns a list of k unique elements from the population.
- random.shuffle(x[, random]): This function shuffles the sequence x in place.
As we see, they all are functions of the Random package. We will now learn about each method one by one with examples:
1) Random.choice()
The random.choice() method returns a randomly chosen element from the given sequence, which can be a list, tuple, or string.
In the below example, we create a variable called letters inside the function that contains all the lowercase letters. We then use the random.choice() function to select a random letter from the letters string and append it to the result_str variable. We repeat this process length times and then return the final result_str.
import random import string def random_string(length): letters = string.ascii_lowercase result_str = ''.join(random.choice(letters) for i in range(length)) return result_str print("The generated random string : ",random_string(6))
Output:
The generated random string : pfzspm
2) Random.choices()
The random.choices() method returns a list of randomly chosen elements from a given sequence but takes an additional 'weights' argument. We pass a list of weights that correspond to the elements of the sequence.
In the below example, weights are provided as a priority for each element in a given list. These weights are then utilized to generate a list of lengths 'k' that contains repeating values for all conceivable values or choices given according to their weights.
import random mylist = ["Tech", "Edutech", "Python"] print(random.choices(mylist, weights = [5, 3, 8], k = 10 ))
Output:
['Python', 'Tech', 'Tech', 'Tech', 'Python', 'Python', 'Tech', 'Python', 'Python', 'Python']
Note: You will get different outputs every time you run this code, as the list is randomly generated using choices().
You can explicitly tell a Python function what kind of string you want or a combination of string types rather than sending it a specific string or list of strings using the below methods of string module ‘import string’.
- String.ascii_uppercase: It returns the string with uppercase.
- String.digits: It returns the string with digits.
- String.punctuation: It returns the string with punctuation
- String.ascii_letters: It returns the string containing various cases.
- String.ascii_lowercase: It returns the string with lowercase.
What is the difference between random.choice() and random.choices()? Even though it may seem that choice() and choices() methods are similar, the difference is choice(seq) returns a single randomly selected element from a sequence, without replacement. While choices(sequence, weights, cum_weights, k) return a list of k randomly selected elements from a sequence, with replacement.
In summary, random.choice() returns a single element, while random.choices() returns a list of elements from a sequence, with the option of specifying the number of elements to choose and the ability to bias the selection using weights or cumulative weights. So, random.choices() is more powerful.
3) Random.sample()
Similar to the previous two functions, this one takes a sequence of elements without replacement and randomly generates a string out of it with a predetermined number of unique elements.
When you need to choose a portion of components from a longer sequence without repeating any of the elements, this method comes in handy. The chosen elements are unique and appear in random order.
import random random_no = random.sample(string.ascii_letters, k=5) print(random_no)
Output:
['a', 'N', 'L', 'I', 'F']
4) Random.shuffle()
A specified list is shuffled so that the elements' order is altered. The function makes changes to the list rather than returning a value. When you need to randomly rearrange the items in a list, it is helpful. For instance, you could use it to shuffle a deck of cards at random or arrange a quiz's questions in random order.
list=['Code', 'Favtutor', 'Machine Learning', 'Students', 'Studies', 'Zebra', 'apple', 'java', 'python', 'tutoring'] random.shuffle(list) print(list)
Output:
['Studies', 'Zebra', 'java', 'python', 'Students', 'Machine Learning', 'apple', 'tutoring', 'Favtutor', 'Code']
The shuffle and sample methods can also be used to shuffling a list in python.
5) StringGenerator Module
Before utilizing this library in Python, you must first install the special library using the "pip command." Using template language assists us in producing a random string of characters. Similar to regular expressions, the template language specifies how to create randomized strings rather than how to match or capture strings.
# pip install StringGenerator from strgen import StringGenerator as SG # Generate random string with 10 characters length word random_str = strgen.StringGenerator("[\w\d]{10}").render() print(random_str) # Generate 5 unique secure tokens, each 8 characters: secure_tokens = SG("[\p\w]{8}").render_set(5) print(secure_tokens,end="\n")
Output:
b31IsB92B5 {'1TdB6sxz', '/W$uHfP$', '8Rf6u#<b', "}H5'hAq:", 'tIu*\\.5/'}
Python Password Generator
While the above methods work wonderfully for generating random strings, they can be less useful for creating unique and safe passwords.
To create cryptographically safe strings, such as passwords, account authentication, security tokens, and related secrets, we have a specific library called "secrets." The most secure source of randomization offered by your operating system is accessible through the secrets module.
The following functions are provided by the secrets module:
- secrets.token_bytes(nbytes): Returns a random byte string containing nbytes number of bytes.
- secrets.token_hex(nbytes): Returns a random string of hexadecimal digits containing nbytes number of bytes.
- secrets.token_urlsafe(nbytes=None): Returns a random URL-safe string containing nbytes number of bytes. If nbytes is not provided, a default value of 16 is used.
These functions generate random values suitable for use as cryptographic keys, tokens, and similar values.
import string import secrets st = string.ascii_letters + string.digits + string.punctuation password = ''.join(secrets.choice(st) for i in range(8)) print(password)
Output:
~2EQ*;3r
A Python password generator is a simple program that can create random, strong, and secure passwords. It should combine random characters, numbers, and symbols.
We will now create a python application to create a random password that meets the following constraints: The password is 12 characters long and contains at least one uppercase letter, one lowercase letter, one digit, and one special character.
Here is the code for the Python Password Generator:
import secrets import string # Define the character set for the password alphabet = string.ascii_letters + string.digits + string.punctuation # Keep generating passwords until we find one that meets the requirements while True: # Generate a random password of length 12 password = ''.join(secrets.choice(alphabet) for i in range(12)) # Check if the password meets the requirements if any(c.islower() for c in password) and any(c.isupper() for c in password) and any(c.isdigit() for c in password) and any(c in "!@#$%^&*()" for c in password): break print(password)
Output:
H]}Lck68T0&%
Additionally, we have token_urlsafe() that generates a hard-to-guess temporary URL containing a security token suitable for password recovery applications. Here is the code:
import secrets # Generate a random token of length 32 bytes token = secrets.token_bytes(32) # Generate a random URL-safe string of length 16 bytes url_safe_string = secrets.token_urlsafe(16) print(token) print(url_safe_string)
Output:
b'\x85\x84H\xd1/\x8bt\xaa\x16\xea\n\x88\xb8\xcbX\xb8\x1fv \xf10\xf8\xbe\x03}\x8e\xc3\x9e\xfb\xfc"\x12' 8XI1EHXi_BrYmWvJhcuisw
Conclusion
Here we discussed a lot of methods for different situations to create a random string using python. However, which method you use would largely depend on your use case. We also created a Python password generator with code. Happy Learning :)