2

Is there any way to generate random alphabets in python. I've come across a code where it is possible to generate random alphabets from a-z.

For instance, the below code generates the following output.

import pandas as pd
import numpy as np
import string

ran1 = np.random.random(5)
print(random)
[0.79842166 0.9632492  0.78434385 0.29819737 0.98211011]

ran2 = string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'

However, I want to generate random letters with input as the number of random letters (example 3) and the desired output as [a, f, c]. Thanks in advance.

1

2 Answers 2

5

Convert the string of letters to a list and then use numpy.random.choice. You'll get an array back, but you can make that a list if you need.

import numpy as np
import string

np.random.seed(123)
list(np.random.choice(list(string.ascii_lowercase), 10))
#['n', 'c', 'c', 'g', 'r', 't', 'k', 'z', 'w', 'b']

As you can see, the default behavior is to sample with replacement. You can change that behavior if needed by adding the parameter replace=False.

0
2

Here is an idea modified from https://pythontips.com/2013/07/28/generating-a-random-string/

import string
import random

def random_generator(size=6, chars=string.ascii_lowercase):
    return ''.join(random.choice(chars) for x in range(size))
4
  • I ran the code and I got the output as a word with random letters (bapxsn). Is there a way to get the output like this [g, t, d]. It should be separated with commas.
    – vivek
    Commented Jul 4, 2018 at 21:37
  • Yes, look here: stackoverflow.com/questions/4978787/… Commented Jul 4, 2018 at 21:39
  • @ALollz shared code that works exactly as I expected and thank you.
    – vivek
    Commented Jul 4, 2018 at 21:39
  • 1
    @vivek This will work in basically the same way. Just call list(random_generator(10)) and you'll get a list of letters. Though since the function joins them, you may just want to change the return to return [random.choice(chars) for x in range(size)] to get the list automatically
    – ALollz
    Commented Jul 4, 2018 at 21:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.