[英]Python regex replace with ASCII value
My input string is something like He#108##108#o
and the output should be Hello
. 我的输入字符串类似于He#108##108#o
,输出应为Hello
。
Basically I want to replace each #[0-9]+#
with the relevant ASCII characters of the number inside the ##
. 基本上我想用##
中的数字的相关ASCII字符替换每个#[0-9]+#
。
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
You can use re.split()
: 你可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.