2

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.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
fiji
  • 228
  • 5
  • 21
  • 2
    You could slice the string and `join` the parts with `'-'`. – mkrieger1 Dec 22 '20 at 01:26
  • Does this answer your question? [Insert some string into given string at given index in Python](https://stackoverflow.com/questions/4022827/insert-some-string-into-given-string-at-given-index-in-python) – Pilot Dec 22 '20 at 01:27
  • See https://docs.python.org/3/tutorial/introduction.html#strings, https://stackoverflow.com/questions/4435169/how-do-i-append-one-string-to-another-in-python – mkrieger1 Dec 22 '20 at 01:28

4 Answers4

11

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
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
2

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
Shenglin Chen
  • 4,504
  • 11
  • 11
1

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
Aplet123
  • 33,825
  • 1
  • 29
  • 55
1

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'
Cainã Max Couto-Silva
  • 4,839
  • 1
  • 11
  • 35