替换替换字符串的命令条件

时间:2016-11-17 20:40:12

标签: python string for-loop replace conditional-statements

想要替换字符串中的某些单词,但要继续获得followinf结果:

字符串:"This is my sentence."

用户输入他们想要替换的内容:"is"

用户输入他们想要替换的内容:"was"

新字符串:"Thwas was my sentence."

我怎样才能确保它只替换"是"而不是它找到的任何字符串?

代码功能:

import string
def replace(word, new_word):
   new_file = string.replace(word, new_word[1])
   return new_file

非常感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:4)

使用正则表达式单词边界:

import re

print(re.sub(r"\bis\b","was","This is my sentence"))

比单纯的分裂更好,因为也使用标点符号:

print(re.sub(r"\bis\b","was","This is, of course, my sentence"))

给出:

This was, of course, my sentence

注意:不要跳过r前缀,否则你的正则表达式会被破坏:\b会被解释为退格。

答案 1 :(得分:1)

一个简单但不那么全面的解决方案(由Jean-Francios Fabre给出),不使用正则表达式。

 ' '.join(x if x != word else new_word for x in string.split())
相关问题