Random string generation with upper case letters and digits

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

提交回复
热议问题