【问题标题】:how to change the python string for example replace one word instead of another?如何更改 python 字符串,例如替换一个单词而不是另一个单词?
【发布时间】:2019-04-07 10:42:12
【问题描述】:

这里的问题是,我有一个 python 字符串,比如“我爱爸爸,我爱妈妈”。在这个字符串中,我想要的是,“我爱妈妈,我爱爸爸”。

这里是python字符串

s='i love dad and  i love mom',
s1=s.replace('dad','mom'),
print(s1)

这里的输出是:我爱妈妈,我爱妈妈

但我需要的输出是:我爱妈妈,我爱爸爸

【问题讨论】:

标签: python python-3.7


【解决方案1】:

用替换创建一个字典

replacements = {
    'daddy': 'mom',
    'mom': 'daddy',
}

创建一个函数以根据匹配对象从字典中返回正确的替换:

def find_replacement(m):
    return replacements[m.group(1)]

然后使用 re.sub

text = "I love daddy and I love mom"
regex = r'({})'.format(r'|'.join(re.escape(w) for w in replacements))
result = re.sub(regex, find_replacement, text)
print(result)

【讨论】:

  • 字符串格式不做单词替换——它只替换格式化占位符,比如{foo}...
猜你喜欢
  • 1970-01-01
  • 2020-09-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 2017-01-22
  • 2017-11-14
  • 2020-10-03
  • 1970-01-01
相关资源
最近更新 更多