python - 在python中使用正则表达式和for循环值替换字符串
问题描述
我想使用第二个变量替换第一个变量的值,但我想保留逗号。我使用了正则表达式,但我不知道它是否可能是因为我还在学习它。所以这是我的代码。
import re
names = 'Mat,Rex,Jay'
nicknames = 'AgentMat LegendRex KillerJay'
split_nicknames = nicknames.split(' ')
for a in range(len(split_nicknames)):
replace = re.sub('\\w+', split_nicknames[a], names)
print(replace)
我的输出是:
KillerJay,KillerJay,KillerJay
我想要这样的输出:
AgentMat,LegendRex,KillerJay
解决方案
我怀疑您正在寻找的内容应该类似于以下内容:
import re
testString = 'This is my complicated test string where Mat, Rex and Jay are all having a lark, but MatReyRex is not changed'
mapping = { 'Mat' : 'AgentMat',
'Jay' : 'KillerJay',
'Rex' : 'LegendRex'
}
reNames = re.compile(r'\b('+'|'.join(mapping)+r')\b')
res = reNames.sub(lambda m: mapping[m.group(0)], testString)
print(res)
执行这个会产生映射的结果:
This is my complicated test string where AgentMat, LegendRex and KillerJay are all having a lark, but MatReyRex is not changed
推荐阅读
- javascript - 试图理解 browser.elementIdText 命令
- python - python - 从 S3(在内存中)解压缩 csv 文件,然后对其进行迭代
- mongodb - 如何在使用 mongodb 时正确处理 promise?
- c# - 缺少编译器所需的成员 Microsoft.CSharp.RuntimeBinder.Binder.Convert
- r - 摆脱R中数据框列名中的数字和点
- excel - VBA 使用输入
- javascript - 处理 Laravel 收到的 XMLHttpRequests 发布请求中结合 json 数据的 javascript FormData
- postgresql - 在网页中嵌入 Heroku 数据剪辑
- r - R studio - 如何按年份对面板中的数据进行分组并求和
- php - 将我的 XML 输出从 Amazon API 转换为 HTML