Python正则表达式替换为ASCII值 [英] Python regex replace with ASCII value

查看:83
本文介绍了Python正则表达式替换为ASCII值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的输入字符串类似于He#108##108#o,输出应该是Hello.

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

基本上我想用##中数字的相关ASCII字符替换每个#[0-9]+#.

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

推荐答案

在正则表达式中使用替换函数,提取数字,将它们转换为整数,然后转换为字符:

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))

结果:

Hello

这篇关于Python正则表达式替换为ASCII值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆