1

How to get uuid of 8 characters only? I did the code line below and got uuid of 36 characters.

id1 = str(uuid.uuid1())
James Z
  • 12,209
  • 10
  • 24
  • 44
charles
  • 209
  • 3
  • 10
  • 2
    A UUID is a 128-bit value; what you see is just one possible representation of that value, namely one using ascii characters only. – chepner Mar 03 '20 at 16:40
  • 2
    Depending on what you mean by "character", what you want ranges from awkward to impossible. A UUID is a 16-byte entity, so each of the 8 "characters" has to be capable of representing a 16-bit entity, something that could have 65536 different "values". – chepner Mar 03 '20 at 16:44
  • Consider MySQL's `uuid_short()`. I think it gives you a 64-bit number. – Rick James Mar 17 '20 at 03:18

3 Answers3

3

Correct answer

The correct answer to this question, as answered here is that it is impossible to generate an 8 character uuid, because uuids are 16 bytes by definition.

The standard for UUIDs is specified in RFC 4221. In the format section, the first words are:

The UUID format is 16 octets

Thank you shudipta-sharma for noting that my original answer would NOT produce a universally unique id.

Old (and incorrect) answer

You could just take the first eight characters.

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

No guarantees about them all being unique.

Community
  • 1
  • 1
kimbo
  • 2,513
  • 1
  • 15
  • 24
1

You can try this:

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.

Ref: https://realpython.com/python-random/

Shudipta Sharma
  • 5,178
  • 3
  • 19
  • 33
0

You can try this, assuming you only want the first 8 characters regardless of object type (python3):

import uuid
id1 = str(uuid.uuid1())
first_eight=id1[:8]
print(first_eight)