A.J.
A.J.

Reputation: 8985

Python uuid4, How to limit the length of Unique chars

In Python, I am using uuid4() method to create a unique char set. But I can not find a way to limit that to 10 or 8 characters. Is there any way?

uuid4()

ffc69c1b-9d87-4c19-8dac-c09ca857e3fc

Thanks.

Upvotes: 18

Views: 36797

Answers (3)

user2226755
user2226755

Reputation: 13159

You can then generate a short UUID with shortuuid:

import shortuuid
shortuuid.uuid()
'vytxeTZskVKR7C7WgdSP3d'

Native solution with big risk of collision:

Try :

x = uuid4()
str(x)[:8]

Output :

"ffc69c1b"

How do I get a substring of a string in Python?

Upvotes: 15

wehnsdaefflae
wehnsdaefflae

Reputation: 906

The previous answers do not provide a UUID, either because they truncate the string or because they didn't generate a UUID to begin with. According to the documentation, if you truncate the string "[t]he IDs won’t be universally unique any longer [...]" and the documentation describes ShortUUID().random() to generate a cryptographically secure string instead of a UUID.

However, you can change the UUID length indirectly by changing the number of characters in the alphabet. In the implementation of ShortUUID.encoded_length() you can see that the UUID length is int(math.ceil(16 * math.log(256) / math.log(len(alphabet)))). You can change the alphabet by shortuuid.set_alphabet().

The more characters in the alphabet, the shorter the UUID can be and still be unique.

Upvotes: 3

mohammed_ayaz
mohammed_ayaz

Reputation: 679

You can use shortuuid package.

pip install shortuuid

then it would be similar to UUID package.

import shortuuid
shortuuid.uuid()

Output

'vytxeTZskVKR7C7WgdSP3d'

Custom Length UUID

shortuuid.ShortUUID().random(length=22)

Output

'RaF56o2r58hTKT7AYS9doj'

Source - https://pypi.org/project/shortuuid/

Upvotes: 14

Related Questions