在我的项目中,我需要能够将字符串中的正则表达式替换为另一个正则表达式。例如,如果我有 2 个正则表达式[a-c]和[x-z],我需要能够将字符串“abc”替换为“xyz”,或者将字符串“hello adan”替换为“hello xdxn”。我该怎么做?
2 回答
![?](http://img1.sycdn.imooc.com/54584ed2000152a202200220-100-100.jpg)
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'
>>>
![?](http://img1.sycdn.imooc.com/533e4d510001c2ad02000200-100-100.jpg)
杨魅力
TA贡献1811条经验 获得超6个赞
尝试使用re.sub
>>>replace = re.sub(r'[a-c]+', 'x','Hello adan')
>>>replace
'Hello xdxn'
>>>re.sub(r'[a-c]+', 'x','Hello bob')
'Hello xox'
添加回答
举报
0/150
提交
取消