>需要生成随机字符串,如下所示
前 5 个字符串应为大写字母 接下来的 4 应该是整数和 终于一个字母
输出我需要示例:
ACCE1664Z
BCED1782V
FBCR9126N
它正在生成随机字符串。
from string import ascii_uppercase, digits
import random
def generatestr():
str0= random.sample(ascii_uppercase,4)+random.sample(digits,4)+random.sample(ascii_uppercase,1)
return ''.join(str0)
print(generatestr())
从@ComplicatedPhenomenon的答案中改进
访问此处了解更多字符串常量(例如ascii_uppercase
(。
假设最后一个字母也是大写的。
import random
def generatestr():
alphabet = []
for letter in range(65, 91):
alphabet.append(chr(letter))
num = [str(i) for i in range(10)]
str0= random.sample(alphabet,4)+random.sample(num,4)+random.sample(alphabet,1)
return ''.join(str0)
generatestr()
import random
import string
def randomString(charLength, intLength):
letters = string.ascii_uppercase
numbers = list(range(0,9))
charArray = ""
numArray= ""
for i in range(max(charLength,intLength)):
if i < charLength:
charArray = charArray + random.choice(letters)
if i < intLength:
numArray = numArray + str(random.choice(numbers))
return (charArray + numArray + random.choice(letters))
print(randomString(5,4))