Random string generation with upper case letters and digits

前端 未结 30 3570
逝去的感伤
逝去的感伤 2020-11-22 02:51

I want to generate a string of size N.

It should be made up of numbers and uppercase English letters such as:

  • 6U1S75
  • 4Z4UKK
  • U911K4
30条回答
  •  余生分开走
    2020-11-22 03:12

    >>> import random
    >>> str = []
    >>> chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    >>> num = int(raw_input('How long do you want the string to be?  '))
    How long do you want the string to be?  10
    >>> for k in range(1, num+1):
    ...    str.append(random.choice(chars))
    ...
    >>> str = "".join(str)
    >>> str
    'tm2JUQ04CK'
    

    The random.choice function picks a random entry in a list. You also create a list so that you can append the character in the for statement. At the end str is ['t', 'm', '2', 'J', 'U', 'Q', '0', '4', 'C', 'K'], but the str = "".join(str) takes care of that, leaving you with 'tm2JUQ04CK'.

    Hope this helps!

提交回复
热议问题