How do you create a random string in Python?

I need it to be number then character, repeating until the iteration is done.

This is what I created:

def random_id(length):
    id = ''
    for i in range(0,length,2):
        id += random.choice(number)
        id += random.choice(alpha)
    return id

Generating strings from (for example) lowercase characters:

import random, string

def randomword(length):
   letters = string.ascii_lowercase
   return ''.join(random.choice(letters) for i in range(length))


>>> randomword(10)
>>> randomword(10)

Since this question is fairly, uh, random, this may work for you:

>>> import uuid
>>> print uuid.uuid4()

>>> import random
>>> import string
>>> s=string.lowercase+string.digits
>>> ''.join(random.sample(s,10))

Answer to the original question:


Quote from:

Return a string of n random bytes suitable for cryptographic use.

This function returns random bytes from an OS-specific randomness
source. The returned data should be unpredictable enough for
cryptographic applications, though its exact quality depends on the OS
implementation. On a UNIX-like system this will query /dev/urandom,
and on Windows it will use CryptGenRandom. If a randomness source is
not found, NotImplementedError will be raised.

For an easy-to-use interface to the random number generator provided
by your platform, please see random.SystemRandom.

You can build random ascii characters like:

import random
print chr(random.randint(0,255))

And then build up a longer string like:

len = 50
print ''.join( [chr(random.randint(0,255)) for i in xrange(0,len)] )

You haven’t really said much about what sort of random string you need. But in any case, you should look into the random module.

A very simple solution is pasted below.

import random

def randstring(length=10):
    return ''.join((random.choice(valid_letters) for i in xrange(length)))

print randstring()
print randstring(20)

In python3.6+ you can use the secrets module:

The secrets module is used for generating cryptographically strong
random numbers suitable for managing data such as passwords, account
authentication, security tokens, and related secrets.

In particularly, secrets should be used in preference to the default
pseudo-random number generator in the random module, which is designed
for modelling and simulation, not security or cryptography.

In testing generation of 768bit security tokens I found:

  • random.choices()0.000246 secs
  • secrets.choice()0.003529 secs

The secrets modules is slower but outside of testing it is what you should be using for cryptographic purposes:

import string, secrets

def random_string(size):        
        letters = string.ascii_lowercase+string.ascii_uppercase+string.digits            
        return ''.join(secrets.choice(letters) for i in range(size))


Sometimes, I’ve wanted random strings that are semi-pronounceable, semi-memorable.

import random

def randomWord(length=5):
    consonants = "bcdfghjklmnpqrstvwxyz"
    vowels = "aeiou"

    return "".join(random.choice((consonants, vowels)[i%2]) for i in range(length))


>>> randomWord()
>>> randomWord()
>>> randomWord(10)

To avoid 4-letter words, don’t set length to 4.


random_name = lambda length: ''.join(random.sample(string.letters, length))

length must be <= len(string.letters) = 53.
result example

   >>> [random_name(x) for x in range(1,20)]
['V', 'Rq', 'YtL', 'AmUF', 'loFdS', 'eNpRFy', 'iWFGtDz', 'ZTNgCvLA', 'fjUDXJvMP', 'EBrPcYKUvZ', 'GmxPKCnbfih', 'nSiNmCRktdWZ', 'VWKSsGwlBeXUr', 'i
stIFGTUlZqnav', 'bqfwgBhyTJMUEzF', 'VLXlPiQnhptZyoHq', 'BXWATvwLCUcVesFfk', 'jLngHmTBtoOSsQlezV', 'JOUhklIwDBMFzrTCPub']

Enjoy. đŸ˜‰

Install this package:

pip3 install py_essentials

And use this code:

from py_essentials import simpleRandom as sr

More informations about the method other parameters are available here.

This function generates random string consisting of upper,lowercase letters, digits, pass the length seperator, no_of_blocks to specify your string format

eg: len_sep = 4, no_of_blocks = 4 will generate the following pattern,


Where, length seperator will add “-” after 4 characters


no of blocks will generate the following patten of characters as string


if a single random string is needed, just keep the no_of_blocks variable to be equal to 1 and len_sep to specify the length of the random string.

eg: len_sep = 10, no_of_blocks = 1, will generate the following pattern ie. random string of length 10,


import random as r

def generate_random_string(len_sep, no_of_blocks):
    random_string = ''
    random_str_seq = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    for i in range(0,len_sep*no_of_blocks):
        if i % len_sep == 0 and i != 0:
            random_string += '-'
        random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
    return random_string

import random 
import string

def get_random_string(size):
    chars = string.ascii_lowercase+string.ascii_uppercase+string.digits
    ''.join(random.choice(chars) for _ in range(size))


output : FfxjmkyyLG5HvLeRudDS