简体   繁体   中英

How to generate random letters in python?

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 az.

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.

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 .

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM