Python regex replace with ASCII value

China☆狼群 提交于 2019-12-30 17:29: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 ##.


回答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


来源:https://stackoverflow.com/questions/45620436/python-regex-replace-with-ascii-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!