Home > Backend Development > Python Tutorial > How to randomly generate a string of uppercase letters and numbers

How to randomly generate a string of uppercase letters and numbers

anonymity
Release: 2019-05-25 11:59:37
Original
6282 people have browsed it

Requirements

Randomly generate a fixed-length combination of uppercase letters and numbers.

How to randomly generate a string of uppercase letters and numbers

Implementation

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import random
def getRandomSet(bits):
    num_set = [chr(i) for i in range(48,58)]
    char_set = [chr(i) for i in range(65,90)]
    total_set = num_set + char_set
    value_set = "".join(random.sample(total_set, bits))
    return value_set
if __name__ == '__main__' :
    strings = getRandomSet(26)
    print(strings)
Copy after login

Analysis

1. First use the chr() function , generate two lists of uppercase letters and numbers

2. Merge the two lists

3. Use the sample sampling function of the random module to randomly collect the specified number of characters.

4. The result of random sampling is a list and needs to be converted into str type. Just use the join function of str.

The above is the detailed content of How to randomly generate a string of uppercase letters and numbers. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template