python - 如何替换字符串中的特定单词
问题描述
我正在尝试在 python 字符串中进行一些替换,我有类似的数据
The lyrics is not that bad!
,我想not that bad
用good
. 这是我拥有的几个数据示例:
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()
然后替换。但没有成功。
解决方案
你可以试试这个:
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 bad
为good
by 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.
推荐阅读
- javascript - 正则表达式 - 至少 6 个字符,包括 2 个特殊字符
- python - Python 和 Dynamics CRM:使用 Web api
- c# - 将结果添加到 TestCaseSource
- sql-server - 如何添加基于子字符串值返回的记录或回车
- c++ - libc.so.6:添加符号时出错:命令行中缺少 DSO
- bash - read -r -a BUILD_ARGS_ARRAY <<< "$@" 在 bash 中是什么意思?
- html - HTML表格自动扩展最后一列以占据剩余宽度
- unity3d - 可以使用 MRKT 和 HTC VIVE 来创建增强现实应用程序吗?
- java - 使用 Platform.runLater 更改非 javafx 线程中的按钮文本
- sql-server - 如何避免此处出现过度拨款警告?或者我什至需要担心它?