Random string generation with upper case letters and digits

前端 未结 30 3205
逝去的感伤
逝去的感伤 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:10

    Use Numpy's random.choice() function

    import numpy as np
    import string        
    
    if __name__ == '__main__':
        length = 16
        a = np.random.choice(list(string.ascii_uppercase + string.digits), length)                
        print(''.join(a))
    

    Documentation is here http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.random.choice.html

    0 讨论(0)
  • 2020-11-22 03:11

    (1) This will give you all caps and numbers:

    import string, random
    passkey=''
    for x in range(8):
        if random.choice([1,2]) == 1:
            passkey += passkey.join(random.choice(string.ascii_uppercase))
        else:
            passkey += passkey.join(random.choice(string.digits))
    print passkey 
    

    (2) If you later want to include lowercase letters in your key, then this will also work:

    import string, random
    passkey=''
    for x in range(8):
        if random.choice([1,2]) == 1:
            passkey += passkey.join(random.choice(string.ascii_letters))
        else:
            passkey += passkey.join(random.choice(string.digits))
    print passkey  
    
    0 讨论(0)
  • 2020-11-22 03:12

    If you need a random string rather than a pseudo random one, you should use os.urandom as the source

    from os import urandom
    from itertools import islice, imap, repeat
    import string
    
    def rand_string(length=5):
        chars = set(string.ascii_uppercase + string.digits)
        char_gen = (c for c in imap(urandom, repeat(1)) if c in chars)
        return ''.join(islice(char_gen, None, length))
    
    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2020-11-22 03:14

    Simply use Python's builtin uuid:

    If UUIDs are okay for your purposes, use the built-in uuid package.

    One Line Solution:

    import uuid; uuid.uuid4().hex.upper()[0:6]

    In Depth Version:

    Example:

    import uuid
    uuid.uuid4() #uuid4 => full random uuid
    # Outputs something like: UUID('0172fc9a-1dac-4414-b88d-6b9a6feb91ea')
    

    If you need exactly your format (for example, "6U1S75"), you can do it like this:

    import uuid
    
    def my_random_string(string_length=10):
        """Returns a random string of length string_length."""
        random = str(uuid.uuid4()) # Convert UUID format to a Python string.
        random = random.upper() # Make all characters uppercase.
        random = random.replace("-","") # Remove the UUID '-'.
        return random[0:string_length] # Return the random string.
    
    print(my_random_string(6)) # For example, D9E50C
    
    0 讨论(0)
  • 2020-11-22 03:15

    I'd do it this way:

    import random
    from string import digits, ascii_uppercase
    
    legals = digits + ascii_uppercase
    
    def rand_string(length, char_set=legals):
    
        output = ''
        for _ in range(length): output += random.choice(char_set)
        return output
    

    Or just:

    def rand_string(length, char_set=legals):
    
        return ''.join( random.choice(char_set) for _ in range(length) )
    
    0 讨论(0)
提交回复
热议问题