Python uuid4, How to limit the length of Unique chars
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/
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.
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?