在Python中,如何替换字符串变量中的一个单词?

在Python中,如何替换字符串变量中的一个单词?,python,python-2.7,replace,substitution,Python,Python 2.7,Replace,Substitution,我知道有人问过如何替换字符串中的单词,但我想替换变量字符串中的特定单词,而不去碰其他单词 例如:如果用户输入“我的家人不喜欢鸡肉”,我希望计算机将“你的家人不喜欢鸡肉”输出给他们。被替换的词是“我的”,替换它的词是“你的”。我正在使用Python 2.7.13。使用字符串方法: >>> "My family does not like chicken".replace("My", "Your") Your family does not like chicken 使用repl

我知道有人问过如何替换字符串中的单词,但我想替换变量字符串中的特定单词,而不去碰其他单词

例如:如果用户输入“我的家人不喜欢鸡肉”,我希望计算机将“你的家人不喜欢鸡肉”输出给他们。被替换的词是“我的”,替换它的词是“你的”。我正在使用Python 2.7.13。

使用字符串方法:

>>> "My family does not like chicken".replace("My", "Your")
Your family does not like chicken
使用replace()函数

输出
您的家人不喜欢鸡肉

其他答案不涉及存储用户输入,您可以在python 2中使用:

#Store users input into a variable
user_input = raw_input("Please enter a sentence: ")

#Use str.replace to replace ALL occurrences of the word "My" with "Your" and output using print
print user_input.replace("My", "Your")
用法示例:

Please enter a sentence:  My family does not like chicken
Your family does not like chicken
试试看


指向python文档的链接:

请向我们展示您在代码中尝试过的内容。如果我们能同时解决你的误解,答案将更有意义。例如,您是否看过
replace()
;它不起作用吗?我误解了replace()的用法。我很抱歉!这正是我需要的。谢谢大家!@那么你应该接受这个答案。单击此答案左侧数字下方的复选标记,它将变为绿色。
Please enter a sentence:  My family does not like chicken
Your family does not like chicken