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

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

    CODE:

    from random import choice
    from string import ascii_uppercase
    
    print(''.join(choice(ascii_uppercase) for i in range(12)))
    

    OUTPUT:

    5 examples:

    QPUPZVVHUNSN
    EFJACZEBYQEB
    QBQJJEEOYTZY
    EOJUSUEAJEEK
    QWRWLIWDTDBD
    

    EDIT:

    If you need only digits, use the digits constant instead of the ascii_uppercase one from the string module.

    3 examples:

    229945986931
    867348810313
    618228923380
    

提交回复
热议问题