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.

Sign up to request clarification or add additional context in comments.

Comments

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 Comments

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.
@ALollz shared code that works exactly as I expected and thank you.
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.