如何生成大小为N的字符串,由数字和大写英文字母组成,例如:
6个754z4英国U911K4型
如何生成大小为N的字符串,由数字和大写英文字母组成,例如:
6个754z4英国U911K4型
当前回答
现在可以在这里使用一个新的库(python>=3.6)
from chancepy import Chance
random_string = Chance.string(length=10, pool="someLettersAndNumbers123")
其他回答
一个简单的例子:
import string
import random
character = string.lowercase + string.uppercase + string.digits + string.punctuation
char_len = len(character)
# you can specify your password length here
pass_len = random.randint(10,20)
password = ''
for x in range(pass_len):
password = password + character[random.randint(0,char_len-1)]
print password
面向安全的方法
我们对任何安全相关的建议都是避免“自己动手”,并使用经过专门安全审查的机密模块。
这来自文档的最佳实践部分:
import string
import secrets
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for i in range(8))
由于您特别要求使用大写字母,因此您可以用ascii_capsaper替换ascii_cletters,或者只使用以下内容将密码大写:
password = password.upper()
不以安全为目的的标准方法
这个问题的规范方法(如指定)使用随机模块中的choices()函数:
>>> from random import choices
>>> from string import ascii_uppercase, digits
>>> population = ascii_uppercase + digits
>>> str.join('', choices(population, k=6))
'6JWF1H'
我会这样做:
import random
from string import digits, ascii_uppercase
legals = digits + ascii_uppercase
def rand_string(length, char_set=legals):
output = ''
for _ in range(length): output += random.choice(char_set)
return output
或者只是:
def rand_string(length, char_set=legals):
return ''.join( random.choice(char_set) for _ in range(length) )
(1) 这将为您提供所有大写和数字:
import string, random
passkey=''
for x in range(8):
if random.choice([1,2]) == 1:
passkey += passkey.join(random.choice(string.ascii_uppercase))
else:
passkey += passkey.join(random.choice(string.digits))
print passkey
(2) 如果您以后想在密钥中包含小写字母,那么这也可以:
import string, random
passkey=''
for x in range(8):
if random.choice([1,2]) == 1:
passkey += passkey.join(random.choice(string.ascii_letters))
else:
passkey += passkey.join(random.choice(string.digits))
print passkey
一种无重复的随机生成器函数,使用一个集合来存储以前生成的值。注意,如果字符串或数量非常大,这将消耗一些内存,而且可能会稍微慢一点。发电机将在给定量或达到最大可能组合时停止。
代码:
#!/usr/bin/env python
from typing import Generator
from random import SystemRandom as RND
from string import ascii_uppercase, digits
def string_generator(size: int = 1, amount: int = 1) -> Generator[str, None, None]:
"""
Return x random strings of a fixed length.
:param size: string length, defaults to 1
:type size: int, optional
:param amount: amount of random strings to generate, defaults to 1
:type amount: int, optional
:yield: Yield composed random string if unique
:rtype: Generator[str, None, None]
"""
CHARS = list(ascii_uppercase + digits)
LIMIT = len(CHARS) ** size
count, check, string = 0, set(), ''
while LIMIT > count < amount:
string = ''.join(RND().choices(CHARS, k=size))
if string not in check:
check.add(string)
yield string
count += 1
for my_count, my_string in enumerate(string_generator(6, 20)):
print(my_count, my_string)
输出:
0 RS9N3P
1 S0GDGR
2 ZNBLFV
3 96FF97
4 38JJZ3
5 Q3214A
6 VLWNK1
7 QMT05E
8 X1ZFP0
9 MZF442
10 10L9AZ
11 GE8HIQ
12 S7PA43
13 MVLXO9
14 YX7Y0G
15 GIIKPF
16 3KCUQA
17 XHIXFV
18 BJQ5VG
19 HQF01Q
如果字符串始终需要包含字母和数字,请使用以下命令:
#!/usr/bin/env python
from typing import Generator
from random import SystemRandom as RND
from string import ascii_uppercase, digits
def string_generator(size: int = 2, amount: int = 1) -> Generator[str, None, None]:
"""
Return x random strings of a fixed length.
:param size: string length, defaults to 1
:type size: int, optional
:param amount: amount of random strings to generate, defaults to 1
:type amount: int, optional
:yield: Yield composed random string if unique
:rtype: Generator[str, None, None]
"""
if size < 2:
print(
'Since the string must contain letters and numbers,',
'its size must be at least two characters',
)
return
CHARS = list(ascii_uppercase + digits)
LIMIT = len(CHARS) ** size
count, check, string = 0, set(), ''
while LIMIT > count < amount:
while 1:
string = ''.join(RND().choices(CHARS, k=size))
if not (string.isalpha() or string.isnumeric()):
break
if string not in check:
check.add(string)
yield string
count += 1
for my_count, my_string in enumerate(string_generator(6, 20)):
print(my_count, my_string)
输出:
0 5JIITL
1 3W7AI1
2 8QMO10
3 ETHAI8
4 BLFPP9
5 50X2CC
6 1LI8WA
7 39CKET
8 R4IM0E
9 Q3KHGS
10 65CBIU
11 XTRHO4
12 N2XIGO
13 06VFCW
14 VE9MJ8
15 A9ADHK
16 Y5ROJ0
17 OH7EJF
18 TQ709S
19 P0DDNJ