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

How to randomly generate a string of uppercase letters and numbers

anonymity
anonymityOriginal
2019-05-25 11:59:376232browse

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)

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!

Statement:
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