在Python中生成一个随机字母

时间:2010-05-12 22:48:44

标签: python random python-3.x

有没有办法在Python中生成随机字母(如random.randint但是用于字母)? random.randint的范围功能会很好但是有一个只输出随机字母的生成器会比没有更好。

21 个答案:

答案 0 :(得分:198)

简单:

>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> import random
>>> random.choice(string.ascii_letters)
'j'

string.ascii_letters根据当前语言环境返回包含小写字母和大写字母的字符串。

random.choice返回序列中的单个随机元素。

答案 1 :(得分:69)

>>> import random
>>> import string
>>> random.choice(string.ascii_letters)
'g'

答案 2 :(得分:23)

>>>def random_char(y):
       return ''.join(random.choice(string.ascii_letters) for x in range(y))

>>>print (random_char(5))
>>>fxkea

生成y个随机字符

答案 3 :(得分:21)

>>> import random
>>> import string    
>>> random.choice(string.ascii_lowercase)
'b'

答案 4 :(得分:9)

另一种方式,为了完整性:

>>> chr(random.randrange(97, 97 + 26))

使用ascii'a'为97的事实,字母表中有26个字母。

在确定random.randrange()函数调用的上限和下限时,请记住random.randrange()在其上限是独占的,这意味着它只生成一个比所提供的整数少1个单位的整数值。

答案 5 :(得分:4)

def randchar(a, b):
    return chr(random.randint(ord(a), ord(b)))

答案 6 :(得分:3)

你可以列一个清单:

import random
list1=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
b=random.randint(0,7)
print(list1[b])

答案 7 :(得分:3)

import random
def guess_letter():
    return random.choice('abcdefghijklmnopqrstuvwxyz')

答案 8 :(得分:2)

您可以使用它来获取一个或多个随机字母

import random
import string
random.seed(10)
letters = string.ascii_lowercase
rand_letters = random.choices(letters,k=5) # where k is the number of required rand_letters

print(letters)

['o', 'l', 'p', 'f', 'v']

答案 9 :(得分:1)

import random
def Random_Alpha():
    l = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
    return l[random.randint(0,25)]

print(Random_Alpha())

答案 10 :(得分:0)

import string
import random

KEY_LEN = 20

def base_str():
    return (string.letters+string.digits)   
def key_gen():
    keylist = [random.choice(base_str()) for i in range(KEY_LEN)]
    return ("".join(keylist))

你可以得到这样的随机字符串:

g9CtUljUWD9wtk1z07iF
ndPbI1DDn6UvHSQoDMtd
klMFY3pTYNVWsNJ6cs34
Qgr7OEalfhXllcFDGh2l

答案 11 :(得分:0)

def create_key(key_len):
    key = ''
    valid_characters_list = string.letters + string.digits
    for i in range(key_len):
        character = choice(valid_characters_list)
        key = key + character
    return key

def create_key_list(key_num):
    keys = []
    for i in range(key_num):
        key = create_key(key_len)
        if key not in keys:
            keys.append(key)
    return keys

答案 12 :(得分:0)

所有先前的答案都是正确的,如果您要查找各种类型的随机字符(即字母数字和特殊字符),那么这是我创建的一个脚本,用于演示创建随机函数的各种类型,它具有三个用于数字的函数,字母字符和特殊字符。该脚本仅生成密码,仅是演示生成随机字符的各种方式的示例。

import string
import random
import sys

#make sure it's 3.7 or above
print(sys.version)

def create_str(str_length):
    return random.sample(string.ascii_letters, str_length)

def create_num(num_length):
    digits = []
    for i in range(num_length):
        digits.append(str(random.randint(1, 100)))

    return digits

def create_special_chars(special_length):
    stringSpecial = []
    for i in range(special_length):
        stringSpecial.append(random.choice('!$%&()*+,-.:;<=>?@[]^_`{|}~'))

    return stringSpecial

print("how many characters would you like to use ? (DO NOT USE LESS THAN 8)")
str_cnt = input()
print("how many digits would you like to use ? (DO NOT USE LESS THAN 2)")
num_cnt = input()
print("how many special characters would you like to use ? (DO NOT USE LESS THAN 1)")
s_chars_cnt = input()
password_values = create_str(int(str_cnt)) +create_num(int(num_cnt)) + create_special_chars(int(s_chars_cnt))

#shuffle/mix the values
random.shuffle(password_values)

print("generated password is: ")
print(''.join(password_values))

结果:

enter image description here

答案 13 :(得分:0)

您可以使用

map(lambda a : chr(a),  np.random.randint(low=65, high=90, size=4))

答案 14 :(得分:0)

一些答案​​的总结和改进。

import numpy as np
n = 5
[chr(i) for i in np.random.randint(ord('a'), ord('z') + 1, n)]
# ['b', 'f', 'r', 'w', 't']

答案 15 :(得分:0)

#*A handy python password generator*

here is the output

 import random
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
        
    print("Welcome to the Python Password Generator!")
    l= int(input("How many letters would you like in your password?\n")) 
    s = int(input(f"How many symbols would you like?\n"))
    n = int(input(f"How many numbers would you like?\n"))
        
    sequence = random.sample(letters,l)
    num      = random.sample(numbers,n)
    sym      = random.sample(symbols,s)
    sequence.extend(num)
    sequence.extend(sym)
         
    random.shuffle(sequence)
    password = ''.join([str(elem) for elem in sequence])#listToStr 
    print(password)

答案 16 :(得分:-1)

好吧,这是我的答案!它运作良好。只需将所需的随机字母数放入“数字”......(Python 3)

import random

def key_gen():
    keylist = random.choice('abcdefghijklmnopqrstuvwxyz')
    return keylist

number = 0
list_item = ''
while number < 20:
    number = number + 1
    list_item = list_item + key_gen()

print(list_item)

答案 17 :(得分:-1)

import string
import random

def random_char(y):
    return ''.join(random.choice(string.ascii_letters+string.digits+li) for x in range(y))
no=int(input("Enter the number of character for your password=  "))
li = random.choice('!@#$%^*&( )_+}{')
print(random_char(no)+li)

答案 18 :(得分:-1)

我的代码过于复杂:

import random

letter = (random.randint(1,26))
if letter == 1:
   print ('a')
elif letter == 2:
    print ('b')
elif letter == 3:
    print ('c')
elif letter == 4:
    print ('d')
elif letter == 5:
    print ('e')
elif letter == 6:
    print ('f')
elif letter == 7:
    print ('g')
elif letter == 8:
    print ('h')
elif letter == 9:
    print ('i')
elif letter == 10:
    print ('j')
elif letter == 11:
    print ('k')
elif letter == 12:
    print ('l')
elif letter == 13:
    print ('m')
elif letter == 14:
    print ('n')
elif letter == 15:
    print ('o')
elif letter == 16:
    print ('p')
elif letter == 17:
    print ('q')
elif letter == 18:
    print ('r')
elif letter == 19:
    print ('s')
elif letter == 20:
    print ('t')
elif letter == 21:
    print ('u')
elif letter == 22:
    print ('v')
elif letter == 23:
    print ('w')
elif letter == 24:
    print ('x')
elif letter == 25:
    print ('y')
elif letter == 26:
    print ('z')

它基本上会从26个随机数中生成一个,然后转换为相应的字母。可以改进它,但是我只是一个初学者,我为这段代码感到自豪。

答案 19 :(得分:-3)

也许这可以帮到你:

import random
for a in range(64,90):
    h = random.randint(64, a)
    e += chr(h)
print e

答案 20 :(得分:-6)

在键盘上放一个蟒蛇让他滚过字母,直到找到你喜欢的随机组合开玩笑!

import string #This was a design above but failed to print. I remodled it.
import random
irandom = random.choice(string.ascii_letters) 
print irandom