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

后端 未结 6 992
感情败类
感情败类 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:46

    #!/bin/python3
    import random
    import string
    def f(n: int) -> str:
            bytes(random.choices(string.ascii_uppercase.encode('ascii'),k=n)).decode('ascii')
    

    run faster for very big n. avoid str concatenate.

提交回复
热议问题