Python find pattern in a string and replace it with other patterned strings in a list

str1 = '(((un5:0,(un7:0,un8:0):15):9,(un4:0,un10:0):10):5,((un6:0,un1:0):10,(un3:0,un9:0,un2:0):14):12):7):0'
list1 = ['un1:21', 'un2:32', 'un3:43', 'un4:3', 'un5:2', 'un6:21', 'un7:3', 'un8:4', 'un9:3', 'un10:2']

There is one string ‘str1’ and one list ‘list1’

I want to change the substring in str1 ‘unX:0’ -> ‘unX:N’

For example, un1:0 -> un1:21, un2:0 -> un2:32….

So the final output has to be

new_str1 = '(((un5:2,(un7:3,un8:4):15):9,(un4:3,un10:2):10):5,((un6:21,un1:21):10,(un3:43,un9:3,un2:32):14):12):7):0'

I think using regex will be a simple solution but I can’t figure it out

Answer

Use re.sub:

d = {re.sub(":d+", ":0", i): i for i in list1}
keys = "|".join(d)
re.sub(keys, lambda x: d[x.group(0)], str1)

Output:

'(((un5:2,(un7:3,un8:4):15):9,(un4:3,un10:2):10):5,((un6:21,un1:21):10,(un3:43,un9:3,un2:32):14):12):7):0'