Как сгенерировать строку uuid - PullRequest
1 голос
/ 13 марта 2019

Используя модуль 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()).

1 Ответ

1 голос
/ 14 марта 2019

Вы можете использовать атрибут .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)
...