How to create a GUID/UUID in Python?

How to create a GUID/UUID in Python?

Asked on November 8, 2018 in Python.
Add Comment


  • 3 Answer(s)

      Use this code:

    >>> import uuid
    >>> uuid.uuid4()
    UUID('bd65600d-8669-4903-8a14-af88203add38')
    >>> str(uuid.uuid4())
    'f50ec0b7-f960-400d-91f0-c42a6d44e3d0'
    >>> uuid.uuid4().hex
    '9fe2c4e93f654fdbb24c02b15259716c
    
    Answered on November 8, 2018.
    Add Comment

      If  Python 2.5 is used, the uuid module is already included with the Python standard distribution.

      For ex:

    >>> import uuid
    >>> uuid.uuid4()
    UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')
    
    Answered on November 8, 2018.
    Add Comment

      Try this code:

    import random as r
    def generate_uuid():
        random_string = ''
        random_str_seq =               "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        uuid_format = [8, 4, 4, 4, 12]
        for n in uuid_format:
            for i in range(0,n):
                random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
            if n != 12:
                random_string += '-'
        return random_string
    
    Answered on November 8, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.