How to Generate Random Numbers and Strings in Python

Python Generate Random Strings Numbers

This article will outline several methods for generating random numbers and strings in the Python programming language.

Generating random values is a common and important task when programming almost any kind of application of moderate complexity.

Random strings and numbers are used to generate unique identifiers (e.g., for the short URLs in URL shortening services), for identifying unique records in a database, and (most importantly) are frequently used to determine the behavior of gameplay elements in video games (for example, simulating a coin flip, or generating random terrain).

The examples in this article are written for Python 3.

Generating Random Numbers

There are several ways to generate random numbers depending on what kind of random number you want to generate.

Python 3 includes the random library, which contains many functions for generating random values, which will be used for the following examples. There’s no need to install anything extra – it comes with Python 3.

Generating Random Integers with randint()

The randint() function generates a random integer and has the following syntax:

randint(start, end)

The function will return an integer number between (and including) the start and end numbers supplied.

The below example generates a random number between 2 and 6 using the randint() function and prints it using the print() function:

import random
print(random.randint(2, 6))

As a result, a random number between 2 and 6 will be printed.

Generating a Random Float Value with random()

A floating-point number is any rational number – it doesn’t have to be an integer, and the decimal place can appear anywhere in the number.

The random() function will generate a random floating-point number between 0 and 1 and has the following syntax:

import random
print(random.random())

A random floating-point number will be printed, for example:

0.59654919358

Picking a Random Integer from a Range of Numbers

Want to pick a random integer from a range of numbers? randrange() can do that. The syntax is:

randrange(start, stop[, step])

Note that:

  • randrange() takes two parameters, with a third optional
    • start and stop must be supplied, and specify the range of integers to pick from
    • The optional step parameter limits the numbers in the range to those in which the number is either the start value or the start value plus a multiple of step.

For example:

import random
print(random.randrange(0, 20, 2))

The above example will pick a number from between the number range 0 to 20 inclusive. However, as the step parameter is supplied with a value of 2, only the value 0 or even numbers from the range will be returned.

Generating Random Bytes/Strings

From Python version 3.9, the randbytes() function can be used to generate a series of random bytes of a given length – this can then be used as a randomized string. The syntax for randbytes() is:

randbytes(n)

Where n is the number of random bytes to generate. Here’s an example:

import random
randomString = randbytes(5).decode()
print(randomString)

Above, randbytes is used to generate random bytes with a length of 5. The decode() method is then used to convert the bytes to a string. The default encoding in Python 3 is UTF-8.

Without randbytes()

If you’re using an older version of Python which doesn’t include the randbytes() function, you can generate a random string using the choice() function.

The choice() function works much like the randrange() function described above – it chooses a random value from a list of supplied values.

import random
alphabet = string.ascii_letters + string.digits
return ''.join(random.choice(alphabet) for i in range(n))

As a few things are happening at once in the above example, I’ll let the comments do the explaining.

Security

If you want to generate random input for authentication or security purposes, ensure you use functions designed specifically for that purpose. Random input, despite the name, can be predictable. Special libraries exist to ensure that secret data is cryptographically secure (or as secure as possible).

The Python secrets library contains functions analogous to the above but with output that can be used in these secure scenarios:

https://docs.python.org/3/library/secrets.html

That said – if you’re building something public-facing, you should not build your own authentication – use a pre-built package made by an expert. Security is too important to wing the implementation using online tutorials.

For more about the random library, see the link below:

For more https://docs.python.org/3/library/random.html

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *