How to insert hyphens into a UUID string?

Question:

I want to create a function that adds a - on position 8, 12, 16, 20 of a UUID string.

Example:

Original: 76684739331d422cb93e5057c112b637
New: 76684739-331d-422c-b93e-5057c112b637

I have no clue on how to position it on multiple positions in a string that wouldn’t look like spaghetti code.

Asked By: fiji

||

Answers:

You can do it by progressively appending on a new string by slicing:

original = "76684739331d422cb93e5057c112b637"
indices = [8, 12, 16, 20]
delimiter = "-"

new_string = ""
prev = 0
for index in indices:
    new_string += original[prev:index] + delimiter
    prev = index
new_string += original[prev:]

print(new_string)
# 76684739-331d-422c-b93e-5057c112b637
Answered By: Aplet123

Given the following arguments:

delimiter = '-'
indexes = [8,12,16,20]
string = '76684739331d422cb93e5057c112b637'

You can use a list comprehension with join:

idx = [0] + indexes + [len(string)]
delimiter.join([string[idx[i]:idx[i+1]] for i in range(len(idx)-1)])

Output:

'76684739-331d-422c-b93e-5057c112b637'

It looks like you are working with UUIDs. There’s a library for that that comes standard with Python:

import uuid
s = '76684739331d422cb93e5057c112b637'
u = uuid.UUID(hex=s)
print(u)
76684739-331d-422c-b93e-5057c112b637
Answered By: Mark Tolonen

Regex is another way, S matches any non-whitespace character, number in {} is numbers of characters.

import re
​
new=re.sub(r'(S{8})(S{4})(S{4})(S{4})(.*)',r'1-2-3-4-5',original)

print(new)

# 76684739-331d-422c-b93e-5057c112b637
Answered By: Shenglin Chen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.