Python: How to generate string of arbitrary length of any alphabet characters

September 14, 2018

I was testing a bug where a field was limited to 255 characters only. I needed to generate a string of more than 255 characters.

The simplest code I found:

# Generate string of only character 'a' 300 times
'a' * 300

This will generate a string of 300 characters

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa......

Or, you can mix characters

'a' * 100 + 'b' * 100 + 'hey master'

Function to Generate strings of arbitrary length

def gen(character, length):
    return character * length

# to use
>>> gen('a',20)
'aaaaaaaaaaaaaaaaaaaa'
>>> gen('a',20) + gen('b',10)
'aaaaaaaaaaaaaaaaaaaabbbbbbbbbb'

Use Random Number library to generate arbitrary string

Using module random

import string
import random

# for upper case ascii characters, and 10 characters long
''.join(random.choice(string.ascii_uppercase) for _ in range(10))

# In a method
def generate(characters=string.ascii_uppercase, length = 10):
    return ''.join(random.choice(characters) for _ in range(length))

>>> generate()
'GSPUYMYMLB'

# For having upper case as well as numerics
>>> generate(characters=string.ascii_uppercase + string.digits)
'X9O814PS58'

# For longer string
>>> generate(characters=string.ascii_uppercase + string.digits, length=20)
'7HCYBJAQP9N48TC179Q8'

Similar Posts

Latest Posts