获取8个字符的UUID

2024-05-13 21:25:41 发布

您现在位置:Python中文网/ 问答频道 /正文

如何仅获取8个字符的uuid? 我做了下面的代码行,得到了36个字符的uuid

id1 = str(uuid.uuid1())

Tags: 代码uuiduuid1str个字符id1
2条回答

正确答案

正如here所回答的,这个问题的正确答案是,不可能生成8个字符的uuid,因为uuid定义为16个字节。

uuid的标准在RFC 4221中指定。在format section中,第一个词是:

The UUID format is 16 octets

谢谢你shudipta-sharma注意到我的原始答案不会产生一个通用的唯一id

旧(不正确)答案

您可以只取前八个字符。

```Python id1=str(uuid.uuid1())[:8] ```

不保证它们都是唯一的。

您可以尝试以下方法:

import string, random

# ''.join() joins the letters from random.choices() into a single Python str of length k.
join=''.join
join(random.choices(string.ascii_letters, k=8)) # Output is like as 'XDCxVAJl'

Resource: Python’s string module contains a number of useful constants: ascii_lowercase, ascii_uppercase, string.punctuation, ascii_whitespace, string.hexdigits and a handful of others.

参考:https://realpython.com/python-random/

相关问题 更多 >