What's the best way to generate random strings of a specific length in Python?

后端 未结 6 993
感情败类
感情败类 2020-12-02 17:05

For a project, I need a method of creating thousands of random strings while keeping collisions low. I\'m looking for them to be only 12 characters long and uppercase only.

6条回答
  •  醉酒成梦
    2020-12-02 17:32

    This function generates random string of UPPERCASE letters with the specified length,

    eg: length = 6, will generate the following random sequence pattern

    YLNYVQ

        import random as r
    
        def generate_random_string(length):
            random_string = ''
            random_str_seq = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            for i in range(0,length):
                if i % length == 0 and i != 0:
                    random_string += '-'
                random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
            return random_string
    

提交回复
热议问题