Generating random strings in python

How to generate a random string in Python

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

Python is a ​powerful language that allows programmers to perform various tasks using built-in libraries. A random string, for example, can be generated using the built-in libraries. Two libraries are imported for this:

import string import random 

Using this random module, different random strings can be generated.

random.choice() is used to generate strings in which characters may repeat, while random.sample() is used for non-repeating characters.

Method Description
string.ascii_uppercase Returns a string with uppercase characters
string.ascii_lowercase Returns a string with lowercase characters
string.ascii_letters Returns a string with both lowercase and uppercase characters
string.digits Returns a string with numeric characters
string.punctuation Returns a string with punctuation characters

Code

import random
import string
# printing lowercase
letters = string.ascii_lowercase
print ( ''.join(random.choice(letters) for i in range(10)) )
# printing uppercase
letters = string.ascii_uppercase
print ( ''.join(random.choice(letters) for i in range(10)) )
# printing letters
letters = string.ascii_letters
print ( ''.join(random.choice(letters) for i in range(10)) )
# printing digits
letters = string.digits
print ( ''.join(random.choice(letters) for i in range(10)) )
# printing punctuation
letters = string.punctuation
print ( ''.join(random.choice(letters) for i in range(10)) )

Learn in-demand tech skills in half the time

Читайте также:  Лучший самоучитель html css

Источник

How to generate a random string in Python?

In this short tutorial, we look at how we can generate a random string in Python. We also look at all the various types of string that can be generated.

Table of Contents: Python Max Function

Importing string and random modules:

In order to generate random strings in Python, we use the string and random modules. The string module contains Ascii string constants in various text cases, digits, etc. The random module on the other hand is used to generate pseudo-random values. In the last method, we would be using the secrets module to help us generate cryptographically secure strings.

Generate random string Python:

Random strings are commonly generated and used widely. Although they serve a large number of use cases, the most common ones are random placeholder usernames, random phone numbers, passwords, etc.

String Module

  1. String.ascii_letters — returns a string of letters containing various cases.
  2. String.ascii_lowercase — returns a string with letters in lowercase.
  3. String.ascii_uppercase — returns a string with letters in uppercase.
  4. String.digits — returns a string containing digits
  5. String.punctuation — returns a string containing punctuations

Random Module:

  • Random.choices — returns elements at random. Here characters can not be unique.
  • Random.sample — returns unique elements.

Code and Explanation:

import random import string print(random.choices(string.ascii_lowercase)) 

This code generated returns one character at random. You can change the string constant method based on the characters you want.

Now let us write the code to generate a string of length 5.

import random import string print(''.join(random.choices(string.ascii_lowercase, k=5))) 

For this, we pass another argument ‘k’ which denotes the size of the string. This method returns a list of characters, and hence we use the join method to convert it into a string.

String in different cases:

In the previous method, we used string.ascii_lowercase. Let us try the letters constantly, we can also concatenate two different types of constants.

Random string in uppercase:

import random import string print(''.join(random.choices(string.ascii_uppercase, k=5))) 

Using String.ascii.letters:

import random import string print(''.join(random.choices(string.ascii_letters, k=5))) 

Concatenating different types of string constants:

import random import string print(''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase, k=5))) 

I haven’t provided output snippets as my output would vary from yours. Also, in all the methods I have used the random.choices. Please feel free to try it out using the random.sample as well.

Cryptographically Secure strings:

While we could use the random method to generate random string in Python, the string generated is not cryptographically secure. Hence it is not recommended while creating temp passwords.

Python versions 3.6 and greater have a better way to generate a cryptographically secure random string. This method makes use of the secrets & string methods. Secrets are very similar to the random method, you can read more about it here.

Code and Explanation:

import secrets import string print(''.join(secrets.choice(string.ascii_uppercase + string.ascii_lowercase) for i in range(7))) 

The secret methods do not have a .choices method which takes a second argument. Hence we use a loop and get the range to the number of characters.

Closing thoughts — Generate random string python:

Both methods can be used to generate a random string in Python. However, which method you use would largely depend on your use case.

A common mistake I have seen beginners make is forgetting to import the module before they use it. Do keep this in mind while you practice using the methods with other string contents.

Источник

How to Generate Random Strings in Python

Python Random String Generation

In this article, we’ll take a look at how we can generate random strings in Python. As the name suggests, we need to generate a random sequence of characters, it is suitable for the random module.

There are various approaches here, so we’ll start from the most intuitive one; using randomized integers.

Build a string from a random integer sequence

As you may know, the chr(integer) maps the integer to a character, assuming it lies within the ASCII limits. (Taken to be 255 for this article)

We can use this mapping to scale any integer to the ASCII character level, using chr(x) , where x is generated randomly.

import random # The limit for the extended ASCII Character set MAX_LIMIT = 255 random_string = '' for _ in range(10): random_integer = random.randint(0, MAX_LIMIT) # Keep appending random characters using chr(x) random_string += (chr(random_integer)) print(random_string, len(random_string))

Sample Output

Here, while the length of the string seems to be 10 characters, we get some weird characters along with newlines, spaces, etc.

This is because we considered the entire ASCII Character set.

If we want to deal with only English alphabets, we can use their ASCII values.

import random random_string = '' for _ in range(10): # Considering only upper and lowercase letters random_integer = random.randint(97, 97 + 26 - 1) flip_bit = random.randint(0, 1) # Convert to lowercase if the flip bit is on random_integer = random_integer - 32 if flip_bit == 1 else random_integer # Keep appending random characters using chr(x) random_string += (chr(random_integer)) print(random_string, len(random_string))

Sample Output

As you can see, now we have only upper and lowercase letters.

But we can avoid all this hassle, and have Python do the work for us. Python has given us the string module for exactly this purpose!

Let’s look at how we can do the same this, using just a couple of lines of code!

Generate Random Strings in Python using the string module

The list of characters used by Python strings is defined here, and we can pick among these groups of characters.

We’ll then use the random.choice() method to randomly choose characters, instead of using integers, as we did previously.

Let us define a function random_string_generator() , that does all this work for us. This will generate a random string, given the length of the string, and the set of allowed characters to sample from.

import random import string def random_string_generator(str_size, allowed_chars): return ''.join(random.choice(allowed_chars) for x in range(str_size)) chars = string.ascii_letters + string.punctuation size = 12 print(chars) print('Random String of length 12 =', random_string_generator(size, chars))

Here, we have specified the allowed list of characters as the string.ascii_letters (upper and lowercase letters), along with string.punctuation (all punctuation marks).

Now, our main function was only 2 lines, and we could randomly choose a character, using random.choice(set) .

Sample Output

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;?@[\]^_`<|>~ Random String of length 12 = d[$Om

We have indeed generated a random string, and the string module allows easy manipulations between character sets!

Make the random generation more secure

While the above random generation method works, if you want to make your function be more cryptographically secure, use the random.SystemRandom() function.

An example random generator function is shown below:

import random import string output_string = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(10)) print(output_string)

This ensures that your string generation is cryptographically secure.

Random UUID Generation

If you want to generate a random UUID String, the uuid module is helpful for this purpose.

import uuid # Generate a random UUID print('Generated a random UUID from uuid1():', uuid.uuid1()) print('Generated a random UUID from uuid4():', uuid.uuid4())

Sample Output

Generated a random UUID from uuid1(): af5d2f80-6470-11ea-b6cd-a73d7e4e7bfe Generated a random UUID from uuid4(): 5d365f9b-14c1-49e7-ad64-328b61c0d8a7

Conclusion

In this article, we learned how we could generate random strings in Python, with the help of the random and string modules.

References

Источник

Оцените статью