如何生成UUID字符串

10

使用uuid模块,我可以生成一个唯一的字符串(例如c389fa3c-3a5c-4d8d-ac92-9b70f2bbe0b5),方法如下:

import uuid
result = uuid.uuid4()
print result 

这将导致:

<class 'uuid.UUID'>

现在,为了获得生成的字符串,我需要调用str()函数:

uuid_string = str(result)
print uuid_string

它会打印:

c389fa3c-3a5c-4d8d-ac92-9b70f2bbe0b5

我想知道是否有更短的方法可以将uuid文本字符串生成为字符串(无需使用str()函数)。


4
“shorter”怎么缩短?str(...)只有5个字符。 - DeepSpace
2
def u(): return str(uuid.uuid4()),调用它u()将非常简短。 - sanyassh
1
@Sanyash 和不必要的“复杂”。 - DeepSpace
2
编写自己的 UUID 生成器 - mad_
1
@DeepSpace 至少会给人一种满足感 - mad_
显示剩余4条评论
1个回答

8
你可以使用.hex属性来获取没有-的字符串值。
In [1]: import uuid

In [2]: result = uuid.uuid4()

In [3]: result.hex
Out[3]: '536bc225eb6d47589b1858f265b809b1'

In [4]: print(result.hex)
536bc225eb6d47589b1858f265b809b1

以下是相关文档:
UUIDs have these read-only attributes:

bytes       the UUID as a 16-byte string (containing the six
            integer fields in big-endian byte order)

bytes_le    the UUID as a 16-byte string (with time_low, time_mid,
            and time_hi_version in little-endian byte order)

fields      a tuple of the six integer fields of the UUID,
            which are also available as six individual attributes
            and two derived attributes:

        time_low                the first 32 bits of the UUID
        time_mid                the next 16 bits of the UUID
        time_hi_version         the next 16 bits of the UUID
        clock_seq_hi_variant    the next 8 bits of the UUID
        clock_seq_low           the next 8 bits of the UUID
        node                    the last 48 bits of the UUID

        time                    the 60-bit timestamp
        clock_seq               the 14-bit sequence number

hex         the UUID as a 32-character hexadecimal string

int         the UUID as a 128-bit integer

urn         the UUID as a URN as specified in RFC 4122

variant     the UUID variant (one of the constants RESERVED_NCS,
            RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE)

version     the UUID version number (1 through 5, meaningful only
            when the variant is RFC_4122)

1
实际上,这不是关于节省一个字符的问题。更多的是在使用给定功能时避免调用不必要的方法。 - rkirmizi
1
何时使用 str(uuid.uuid4()) 和何时使用 uuid.uuid4().hex - Deepam Gupta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接