按照字符串生成格式 - 随机顺序

时间:2021-01-06 06:41:16

标签: python python-3.x random

手头的问题

目前,由于与问题无关的原因,我正在努力制作代码生成器。

代码遵循00|letter|8string mix|letter

的格式

预期最终结果的示例如下:

00b06c1161bc 00aee797645b

00c435ab439e 00da494a229a

中间 8 节字符串的快速细分导致最多需要两个字母字符和 6 个可以随机排列的数字。

虽然我对此有困难,但接受的信件数量有限。这些是字母 abcdef

我已经为生成器创建了一个列表 (acceptedChars=["a","b","c","d","e","f"]),但是如何允许它按照我不确定如何实现的要求使用它来生成。

关于这方面的任何信息都会很棒,如果您有任何问题,请发表评论,我一定会回复。

4 个答案:

答案 0 :(得分:1)

我认为 random.choice 是您想要的:

import random
acceptedChars = ["a","b","c","d","e","f"]
x = random.choice(acceptedChars)
y = random.choice(acceptedChars)

答案 1 :(得分:1)

这是使用随机函数的代码的完整实现。

此代码将生成 100 个随机的 12 个字符代码。

下面的代码还解决了 requirement of a maximum of two alpha-characters and 6 numbers that can be in random order

import random

acceptedChars = list('abcdef')
acceptedDigit = list('0123456789')

for i in range(100):
    secretCode = '00' + random.choice(acceptedChars)
    charCount = digitCount = 0

    pos1 = random.randint(1,8)
    pos2 = pos1
    while pos2 == pos1: pos2 = random.randint(1,8)

    for i in range(1,9):
        if i in (pos1,pos2):
            secretCode += random.choice(acceptedChars)
        else:
            secretCode += random.choice(acceptedDigit)

    secretCode += random.choice(acceptedChars)

    print (secretCode)

随机代码的样本输出(生成 10 个):

00e89642be3c
00ba75d2130e
00b56c9b906b
00da9294e87c
00b3664ce97f
00c4b6681a3e
00e6699f75cf
00d369d07a0a
00ce653a228f
00d5665f95bd

答案 2 :(得分:1)

检查整个代码以解决您的问题。也许你会发现一些有用的东西。我的复杂度低于 O(n2)。

验证随机字符串生成程序。 此代码还满足最多 2 个 alpha 要求。

import random
def code():
    acceptedChars=["a","b","c","d","e","f"]
    first = "00"
    second = random.choice(acceptedChars)
    third = ""
    fourth = random.choice(acceptedChars) 

    # for third part

    slot = random.randint(0,2)
    if (slot == 2):
        number = str(random.randint(100000,1000000))
        alpha1 = random.choice(acceptedChars)
        alpha2 = random.choice(acceptedChars)
        part1 = random.randint(0,6)
        part2 = random.randint(part1,6)
        third = number[:part1] + alpha1 + number[part1:part2] + alpha2 + number[part2:]
    elif (slot == 1):
        number = str(random.randint(1000000,10000000))
        alpha = random.choice(acceptedChars)
        slot = random.randint(0,8)
        third = number[:slot] + alpha + number[slot:]
    else:
        third = str(random.randint(10000000,100000000))

    
    return first + second + third + fourth


print(code())

希望有帮助。

输出看起来像:

00d65262056f
00a317c8015e
00a334564ecf
00e14a657d9c

答案 3 :(得分:0)

import string
import random

allowed_chars = string.ascii_letters[:6]

expression = ''.join(random.choices(allowed_chars + string.digits, k=8))
print(f"The generator is 00{str(expression)}")
相关问题