Use python to specify a number to randomly generate a set of mixed character sets

I want to generate a mixed id or password for testing today. I have thought about many ways, such as adding a datetime library, and then intercepting a part, or randomly generating a part, replacing, and adding.

Here is a simple and understandable way

1. Demonstration of running results

This is the effect:

How many digits are generated: 18
^ry3Gu#aVr8VV(41%8

u1i2T!KsT~%^6Faf61

2. Implementation steps

1. First import the random library, which is named r here

import random as r

2. Then because I want to dope letters, numbers, characters, etc. that contain upper and lower case, I take the method of string to do it

S_list = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ01234567890123456789+-*/.,!`~@#$%^&*()="

Here, in order to increase the number of numbers that appear, I added a few more groups, and then consider using the choice in random to randomly select one and perform a loop

3. Then define a list function, use o as the original data of the list for subsequent replacement, here range(1,a), a is input by the user

def list_x():
    o = r.choice(S_list)
    y = [o]
    for i in range(1, a):
        y[i] = y.append(o)
    return y

4. Define another function, call the list function nestedly, pass the value added in the list_x() function to m in an iterative manner, and assign a value to each subscript cycle

def rand_code(n):
    m = list_x()
    for i in range(1, n):
        m[i] = r.choice(S_list)

    return m

5. Finally, call the main function and use map to convert to string format output

a = int(input("生成多少位数:"))
x = rand_code(a)
x = ''.join(map(str, x))
print(x)

3. Complete code

# _*_ coding:utf-8 _*_
# @Time    : 2022/9/7 16:56
# @Author  : ice_Seattle
# @File    : 随机id.py
# @Software: PyCharm


import random as r
S_list = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ01234567890123456789+-*/.,!`~@#$%^&*()="


def list_x():
    o = r.choice(S_list)
    y = [o]
    for i in range(1, a):
        y[i] = y.append(o)
    return y


def rand_code(n):
    m = list_x()
    for i in range(1, n):
        m[i] = r.choice(S_list)

    return m


a = int(input("生成多少位数:"))
x = rand_code(a)
x = ''.join(map(str, x))
print(x)


operation result

How many digits to generate: 12
X5cVX83, U=74

Four. Go crazy:

A lot of output, only part of the screenshot

Extended idea: algorithmic encryption can be performed on the corresponding generated characters, it must be fun

Guess you like

Origin blog.csdn.net/qq_53521409/article/details/126753094