猿问

正则表达式替换 Python

在我的项目中,我需要能够将字符串中的正则表达式替换为另一个正则表达式。

例如,如果我有 2 个正则表达式[a-c][x-z],我需要能够将字符串“abc”替换为“xyz”,或者将字符串“hello adan”替换为“hello xdxn”。我该怎么做?


慕尼黑的夜晚无繁华
浏览 112回答 2
2回答

MMMHUHU

我们绘制地图,然后逐字翻译。当对字典使用 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'>>>

杨魅力

尝试使用re.sub>>>replace = re.sub(r'[a-c]+', 'x','Hello adan')>>>replace'Hello xdxn'>>>re.sub(r'[a-c]+', 'x','Hello bob')'Hello xox'
随时随地看视频慕课网APP

相关分类

Python
我要回答