Sunday, May 25, 2014

How to convert UUID to String in Python!!!



              A universally unique identifier (UUID) is an identifier standard used in software construction, standardized by the Open Software Foundation (OSF) as part of the Distributed Computing Environment (DCE). Check here for more details.

             I recently faced a  scenario where I need to use string format of the UUID value. I searched in google and could not find proper answer. Finally I got the solution and here it is. After Creating a UUID, we can get different different values depending on the format. For example, we can get int, hex and byte values of UUID. Similarly using urn (Uniform resource name), we can get the string value of the UUID as shown below.

>>> uid = uuid.uuid1() #creating UUID
>>> uid 
UUID('52f8e1ba-e3ac-11e3-8232-a82066136178')
>>> uid.int #int format of UUID
110288963624339905056441828728831697272L
>>> uid.hex  #hexa format of UUID
'52f8e1bae3ac11e38232a82066136178'
>>> uid.bytes  #bytes format of UUID
'R\xf8\xe1\xba\xe3\xac\x11\xe3\x822\xa8 f\x13ax'
>>> uid.urn #uniform resource name
'urn:uuid:52f8e1ba-e3ac-11e3-8232-a82066136178'
>>> 

From the above example uid.urn returns string value 'urn:uuid:52f8e1ba-e3ac-11e3-8232-a82066136178'. But we need only value and we dont need first nine characters 'urn:uuid:', so we can skip those 9 characters to get the string value as shown below.

>>> uid_str = uid.urn
>>> str = uid_str[9:]
>>> str
'52f8e1ba-e3ac-11e3-8232-a82066136178'
>>> 

Happy Coding!!!

7 comments:

Unknown said...

simply

str(uid)

is enough

Chanduthedev p said...

Thanks Alex for simple way to get uid in string format.

Anonymous said...

I felt off my chain just reading this, you manually trip characters from a string? Just use str function, it totally works

here is sample even with JSONpretty dump added


import uuid
import json

mydict = { "myuuid" : str(uuid.uuid1()) }
json.dumps(mydict)

MuddyWat said...

I get this:
b'\xf43\x97\x17\xcc\x17\xaeD\xaa\xe7=M\x16\xbe\x1d\xb0'
when I query Oracle in Python 3 it for field that is a guid. The actual GUID looks should be this:
F4339717CC17AE44AAE73D4D16BE1DB0
From this post it seems I should be able to do this:
str('\xf43\x97\x17\xcc\x17\xaeD\xaa\xe7=M\x16\xbe\x1d\xb0')
to get back to the original. But what I get is this:
WÕxueEŒ /¿ ­v
Which is not useful at all.

Any thoughts?

David Okwii said...

Thanks dude for this. Helped me out.

markson said...

AnyConv is very easy to use. Just visit their website, upload your original files, choose the format you want to convert them to, and then hit Convert Now. Converted files can be downloaded immediately. AnyConv

Keen Solution said...

Hire Java Developers in india

Popular Posts