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.

vivek
  • 563
  • 7
  • 16
  • Possible duplicate of [How do I generate a random string (of length X, a-z only) in Python?](https://stackoverflow.com/questions/1957273/how-do-i-generate-a-random-string-of-length-x-a-z-only-in-python) – vahdet Jul 04 '18 at 21:22

2 Answers2

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.

ALollz
  • 57,915
  • 7
  • 66
  • 89
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))
nathanscain
  • 121
  • 5
  • 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 Jul 04 '18 at 21:37
  • Yes, look here: https://stackoverflow.com/questions/4978787/how-to-split-a-string-into-array-of-characters – nathanscain Jul 04 '18 at 21:39
  • @ALollz shared code that works exactly as I expected and thank you. – vivek Jul 04 '18 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 Jul 04 '18 at 21:43