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

在python中使用正则表达式和for循环值替换字符串

在python中使用正则表达式和for循环值替换字符串

慕无忌1623718 2022-07-12 10:02:11
我想使用第二个变量替换第一个变量的值,但我想保留逗号。我使用了正则表达式,但我不知道它是否可能是因为我还在学习它。所以这是我的代码。import renames = '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
查看完整描述

2 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

我怀疑您正在寻找的内容应该类似于以下内容:


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


查看完整回答
反对 回复 2022-07-12
?
皈依舞

TA贡献1851条经验 获得超3个赞

我们可以如下构建映射:


import re

names = 'Mat,Rex,Jay'

nicknames = 'AgentMat LegendRex KillerJay'


my_dict = dict(zip(names.split(','), nicknames.split(' ')))


replace = re.sub(r'\b\w+\b', lambda m:my_dict[m[0]], names)

print(replace)

然后使用 lambda 应用映射。


查看完整回答
反对 回复 2022-07-12
  • 2 回答
  • 0 关注
  • 231 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号