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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With