Search code examples
pythonuuid

How to Create UUID with dashes, instead of without dashes using uuid-package for Python 3.6?


I am using python v3.6, in Odoo framework.

I wanted to generate uuid, so I am using uuid as follows:

:~$ python3
Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import uuid
>>> id =  uuid.uuid1().hex
>>> id
'daf59b684d6a11xz9a9c34028611c679'
>>> 

How can I get uuid? separated by hyphens and dividing string into four parts as : daf59b684-d6a11x-z9a9c3402-8611c679

I tried finding it on SO, but didn't get, instead got a reverse-one, opposite of my requirements as link.

how to create hyphens in betweens uuid-string, like this??

UUID-Docs link.


Solution

  • You just want to convert the UUID into a string:

    >>> import uuid
    >>> print(uuid.uuid1())
    74ba3af4-4d6d-11ea-989f-784f435149ee
    >>> u = str(uuid.uuid1())
    >>> u
    '7d7b626c-4d6d-11ea-989f-784f435149ee'
    

    Note that this is clearly documented:

    str(uuid) returns a string in the form 12345678-1234-5678-1234-567812345678 where the 32 hexadecimal digits represent the UUID.