12

My input string is something like He#108##108#o and the output should be Hello.

Basically I want to replace each #[0-9]+# with the relevant ASCII characters of the number inside the ##.

2 Answers 2

18

Use a replacement function in your regex, which extracts the digits, converts them to integer, and then to character:

import re

s = "He#108##108#o"

print(re.sub("#(\d+)#", lambda x : chr(int(x.group(1))), s))

Result:

Hello
0
6

You can use re.split():

import re

s = "He#108##108#o"

new_s = re.split("#+", s)

final_s = ''.join(chr(int(i)) if i.isdigit() else i for i in new_s)

Output:

Hello