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

如何替换字符串的多个子字符串?

如何替换字符串的多个子字符串?

翻翻过去那场雪 2019-06-09 14:11:45
如何替换字符串的多个子字符串?我想使用.替换函数替换多个字符串。我现在string.replace("condition1", "")但我想要的是string.replace("condition1", "").replace("condition2", "text")虽然这感觉不像是好的语法做这件事的正确方法是什么?有点像grep/regex中你能做什么\1和\2将字段替换为某些搜索字符串
查看完整描述

3 回答

?
慕雪6442864

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

下面是一个应该使用正则表达式的简短示例:

import re

rep = {"condition1": "", "condition2": "text"} # define desired replacements here# use these three lines to do the replacementrep 
= dict((re.escape(k), v) for k, v in rep.iteritems()) #Python 3 renamed dict.iteritems to dict.items so use rep.items()
 for latest versionspattern = re.compile("|".join(rep.keys()))text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)

例如:

>>> pattern.sub(lambda m: rep[re.escape(m.group(0))], "(condition1) and --condition2--")'() and --text--'


查看完整回答
反对 回复 2019-06-09
?
牛魔王的故事

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

你可以做一个很好的循环功能。

def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text

哪里text是完整的字符串和dic是一个字典-每个定义都是一个字符串,将取代一个匹配的术语。

在Python 3中,iteritems()已被替换为items()


小心:Python字典没有可靠的迭代顺序。只有在以下情况下,此解决方案才能解决问题:

  • 替换顺序无关
  • 更换之前的替换结果是可以的

例如:

d = { "cat": "dog", "dog": "pig"}mySentence = "This is my cat and this is my dog."replace_all(mySentence, d)print(mySentence)

可能的产出#1:

"This is my pig and this is my pig."

可能的输出#2

"This is my dog and this is my pig."

一个可能的解决方法是使用OrderedDict。

from collections import OrderedDictdef replace_all(text, dic):
    for i, j in dic.items():
        text = text.replace(i, j)
    return text
od = OrderedDict([("cat", "dog"), ("dog", "pig")])mySentence = "This is my cat and this is my dog."replace_all(mySentence, od)
print(mySentence)

产出:

"This is my pig and this is my pig."

小心#2:如果你text字符串太大了,或者字典里有很多对。


查看完整回答
反对 回复 2019-06-09
?
开心每一天1111

TA贡献1836条经验 获得超13个赞

下面是第一种解决方案的变体,如果您喜欢功能的话,可以使用Reduce。*)

repls = {'hello' : 'goodbye', 'world' : 'earth'}s = 'hello, world'reduce(lambda a, kv: a.replace(*kv), repls.iteritems(), s)

马丁诺的更好版本:

repls = ('hello', 'goodbye'), ('world', 'earth')s = 'hello, world'reduce(lambda a, kv: a.replace(*kv), repls, s)


查看完整回答
反对 回复 2019-06-09
  • 3 回答
  • 0 关注
  • 649 浏览
慕课专栏
更多

添加回答

举报

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