【问题标题】:python: how to convert a valid uuid from String to UUID?python:如何将有效的 uuid 从 String 转换为 UUID?
【发布时间】:2013-03-29 08:35:03
【问题描述】:

我收到的数据是

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

我需要将uuid 从String 转换为uuid

我在python docs 上没有找到方法,还是我在这里遗漏了一些基本的东西?

【问题讨论】:

标签: python uuid


【解决方案1】:

将 UUID 转换为字符串

import uuid

uuid_value_in_string=str(uuid.uuid4())

如需了解有关 UUID 的更多信息: https://www.copilotcode.com/2021/12/get-unique-id-string-or-numberuuid-in.html

【讨论】:

  • 可行,但 OP 想要将 str 转换为 uuid 而不是 uuid 转换为 str。
【解决方案2】:

除非您需要该 uuid 的字符串表示形式,否则不要在 UUID 对象上调用 .hex。

>>> 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'>

然后像上面提到的将 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

您甚至可以设置一个小型辅助实用程序函数来验证 str 并返回 UUID(如果您愿意):

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

然后使用它:

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

【讨论】:

    【解决方案3】:

    如果上述答案不适用于您将字符串格式的有效 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'>
    

    【讨论】:

      【解决方案4】:

      只需将其传递给uuid.UUID:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-05
        • 1970-01-01
        • 1970-01-01
        • 2018-02-09
        相关资源
        最近更新 更多