gpt4 book ai didi

python - 如何删除或替换由起点和终点确定的 Python 中的子字符串?

转载 作者:行者123 更新时间:2023-11-28 19:56:39 24 4
gpt4 key购买 nike

有时我会删除或替换一个长字符串的子字符串。因此,我将确定一个开始模式和一个结束模式,这将确定子字符串的起点和终点:

long_string = "lorem ipsum..white chevy..blah,blah...lot of text..beer bottle....and so to the end"
removed_substr_start = "white chevy"
removed_substr_end = "beer bott"

# this is pseudo method down
STRresult = long_string.replace( [from]removed_substr_start [to]removed_substr_end, "")

最佳答案

我猜你想要类似的东西,没有正则表达式:

def replace_between(text, begin, end, alternative=''):
middle = text.split(begin, 1)[1].split(end, 1)[0]
return text.replace(middle, alternative)

未测试,您应该保护第一行免受异常(如果未找到开始或结束),但想法就在这里 :)

关于python - 如何删除或替换由起点和终点确定的 Python 中的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17920366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com