python:如何将有效的 uuid 从字符串转换为 UUID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15859156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:12:25  来源:igfitidea点击:

python: how to convert a valid uuid from String to UUID?

pythonuuid

提问by daydreamer

I receive the data as

我收到的数据为

   {
        "name": "Unknown",
        "parent": "Uncategorized",
        "uuid": "06335e84-2872-4914-8c5d-3ed07d2a2f16"
    },

and I need to convert the uuidfrom Stringto uuid

我需要将uuidfrom转换Stringuuid

I did not find a way on the python docs, or am I missing something basic here?

我没有在python 文档上找到方法,或者我在这里遗漏了一些基本的东西?

采纳答案by Blender

Just pass it to uuid.UUID:

只需将其传递给uuid.UUID

import uuid

o = {
    "name": "Unknown",
    "parent": "Uncategorized",
    "uuid": "06335e84-2872-4914-8c5d-3ed07d2a2f16"
}

print uuid.UUID(o['uuid']).hex

回答by Weezy.F

If the above answer didn't work for you for converting a valid UUID in string format back to an actual UUID object... using uuid.UUID(your_uuid_string)worked for me.

如果上述答案对您将字符串格式的有效 UUID 转换回实际 UUID 对象不起作用...使用uuid.UUID(your_uuid_string)对我有用。

In [6]: import uuid
   ...:
   ...: o = {
   ...:     "name": "Unknown",
   ...:     "parent": "Uncategorized",
   ...:     "uuid": "06335e84-2872-4914-8c5d-3ed07d2a2f16"
   ...: }
   ...:
   ...: print uuid.UUID(o['uuid']).hex
   ...: print type(uuid.UUID(o['uuid']).hex)
06335e84287249148c5d3ed07d2a2f16
<type 'str'>

In [7]: your_uuid_string = uuid.UUID(o['uuid']).hex

In [8]: print uuid.UUID(your_uuid_string)
06335e84-2872-4914-8c5d-3ed07d2a2f16

In [9]: print type(uuid.UUID(your_uuid_string))
<class 'uuid.UUID'>

回答by slajma

Don't call .hexon the UUID object unless you need the string representation of that uuid.

不要调用.hexUUID 对象,除非您需要该 uuid 的字符串表示。

>>> import uuid
>>> some_uuid = uuid.uuid4()
>>> type(some_uuid)
<class 'uuid.UUID'>
>>> some_uuid_str = some_uuid.hex
>>> some_uuid_str
'5b77bdbade7b4fcb838f8111b68e18ae'
>>> type(some_uuid_str)
<class 'str'>

Then as others mentioned above to convert a uuid string back to UUID instance do:

然后正如上面提到的将 uuid 字符串转换回 UUID 实例的其他人所做的:

>>> uuid.UUID(some_uuid_str)
UUID('5b77bdba-de7b-4fcb-838f-8111b68e18ae')
>>> (some_uuid == uuid.UUID(some_uuid_str))
True
>>> (some_uuid == some_uuid_str)
False

You could even set up a small helper utility function to validate the strand return the UUID back if you wanted to:

如果需要,您甚至可以设置一个小的辅助实用程序函数来验证str并返回 UUID:

def is_valid_uuid(val):
    try:
        return uuid.UUID(str(val))
    except ValueError:
        return None

Then to use it:

然后使用它:

>>> some_uuid = uuid.uuid4()
>>> is_valid_uuid(some_uuid)
UUID('aa6635e1-e394-463b-b43d-69eb4c3a8570')
>>> type(is_valid_uuid(some_uuid))
<class 'uuid.UUID'>