Python regex replace with ASCII value

2019-02-21 10:34发布

问题:

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 ##.

回答1:

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


回答2:

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