首页 > 解决方案 > 如何替换字符串中的特定单词

问题描述

我正在尝试在 python 字符串中进行一些替换,我有类似的数据 The lyrics is not that bad!,我想not that badgood. 这是我拥有的几个数据示例:

I HAVE THIS  --  WANT TO CONVERT LIKE THIS
The lyrics is not that bad!  --  The lyrics is good!
Food is not bad.  --  Food is good.
!! not !! bad !!  --  !! good !!
notbad  --  good
The song is not extremely gently bad for my ears.  --  The song is good for my ears.
The sight is not very very bad.  -- The sight is good.

我正在尝试编写一些适用于所有人的通用脚本。我是 python 的新手,我尝试过str.replace(),查找str.find()然后替换。但没有成功。

标签: pythonpython-3.xreplace

解决方案


你可以试试这个:

string=input("Enter string")
#Input from user is :
string="The lyrics is not that bad!"
string=string.replace("not that bad","good")
print(string)
# The lyrics is good!

这里我们要求用户输入字符串,用户输入The lyrics is not that bad!现在我们必须替换not that badgoodby string.replace("not that bad","good")
编辑:
如果你想概括,我在你的字符串中找到了一些模式。就像您想用“好”替换“不”和“坏”之间的文本。所以,你可以试试这个:

import re

string=input("Enter string")

#Input from user is :
string="The sight is not very very bad."
string="Food is not bad."
string="The song is not extremely gently bad for my ears."

string=re.sub("not(.*?)bad","good",string)

print(string)
# The sight is good.
# Food is good.
# The song is good for my ears.

推荐阅读