Python uuid
时间: 2023-11-05 13:05:35 浏览: 77
uuid
The uuid module in Python is used to generate unique identifiers. UUID stands for "Universally Unique Identifier". UUIDs are used in many applications as unique identifiers for objects, data records, and other entities.
To use the uuid module, you first need to import it:
```python
import uuid
```
Once you have imported the uuid module, you can generate a UUID using the `uuid.uuid4()` method:
```python
my_uuid = uuid.uuid4()
print(my_uuid)
```
This will generate a random UUID and print it to the console.
You can also generate a UUID based on a namespace and a name using the `uuid.uuid5()` method:
```python
namespace = uuid.UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')
name = 'example'
my_uuid = uuid.uuid5(namespace, name)
print(my_uuid)
```
This will generate a UUID based on the namespace and name provided.
UUIDs are typically represented as strings of 32 hexadecimal digits separated by hyphens. However, you can also convert a UUID to a bytes object using the `bytes()` method:
```python
my_uuid = uuid.uuid4()
my_bytes = bytes(my_uuid)
print(my_bytes)
```
This will convert the UUID to a bytes object and print it to the console.
阅读全文