为了账号安全,请及时绑定邮箱和手机立即绑定

正则表达式替换 Python

正则表达式替换 Python

慕尼黑的夜晚无繁华 2023-09-26 16:09:13
在我的项目中,我需要能够将字符串中的正则表达式替换为另一个正则表达式。例如,如果我有 2 个正则表达式[a-c]和[x-z],我需要能够将字符串“abc”替换为“xyz”,或者将字符串“hello adan”替换为“hello xdxn”。我该怎么做?
查看完整描述

2 回答

?
MMMHUHU

TA贡献1834条经验 获得超8个赞

我们绘制地图,然后逐字翻译。当对字典使用 get 时,第二个参数指定如果找不到则返回什么。


>>> trans = dict(zip(list("xyz"),list("abc")))

>>> trans

{'x': 'a', 'y': 'b', 'z': 'c'}

>>> "".join([trans.get(i,i) for i in "hello xdxn"])

'hello adan'

>>>

或者更改 trans 中的顺序以朝其他方向走


>>> trans = dict(zip(list("abc"),list("xyz")))

>>> trans

{'a': 'x', 'b': 'y', 'c': 'z'}

>>> "".join([trans.get(i,i) for i in "hello adan"])

'hello xdxn'

>>>


查看完整回答
反对 回复 2023-09-26
?
杨魅力

TA贡献1811条经验 获得超5个赞

尝试使用re.sub

>>>replace = re.sub(r'[a-c]+', 'x','Hello adan')

>>>replace

'Hello xdxn'

>>>re.sub(r'[a-c]+', 'x','Hello bob')

'Hello xox'


查看完整回答
反对 回复 2023-09-26
  • 2 回答
  • 0 关注
  • 85 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信