2024-07-06 22:09:25 发布
网友
我正在尝试用子字符串“cat”替换子字符串“gta”。但条件是“gta”后面必须紧跟子字符串“dog”。你知道吗
示例:“gtagtadogcat”将变为“gtacatdogcat”
我正在努力的部分是试图编写程序来找到“gta”,并验证“dog”是幕后黑手,如果是真的,则将“gta”改为“cat”。你知道吗
你可以使用正则表达式:
re.sub('gta(dog)', r'cat\1', 'gtagtadogcat')
输出:
'gtacatdogcat'
*编辑:如果你放入整个字符串,你就不需要forloop了。举个例子:
re.sub('gta(dog)', r'cat\1', 'gtagtadogcat_moretextgta_lastgtadog')
'gtacatdogcat_moretextgta_lastcatdog'
>>> 'gtagtadogcat'.replace('gta'+'dog', 'cat'+'dog') 'gtacatdogcat'
old_string = 'gtagtadogcat' print(old_string.replace('gtacat','dogcat'))
输出:gtagtadogcat
gtagtadogcat
你可以使用正则表达式:
输出:
*编辑:如果你放入整个字符串,你就不需要forloop了。举个例子:
输出:
输出:
gtagtadogcat
相关问题 更多 >
编程相关推荐