You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中替换或删除两个指定子串及其间的内容

How to Remove Substring Between Two Fixed Start/End Strings (Inclusive)

To solve your problem of stripping out the substring from 'the' to 'intending' (including both) and getting 'This is to edit', here are two straightforward, practical methods in Python:

Method 1: Regular Expressions (Robust for General Cases)

Regex is ideal here because it handles edge cases (like special characters in your start/end substrings) and can easily adapt if you need to process multiple occurrences across your corpus.

import re

origSent = 'This is the sentence I am intending to edit'
start_sub = 'the'
end_sub = 'intending'

# Escape special regex characters to avoid pattern breaks (safe practice)
pattern = re.compile(f"{re.escape(start_sub)}.*?{re.escape(end_sub)}")
newSent = pattern.sub('', origSent)

print(newSent)  # Output: 'This is to edit'

Quick Notes:

  • re.escape() ensures characters like ., *, or ? in your start/end substrings don't interfere with the regex pattern.
  • .*? uses non-greedy matching—it stops at the first occurrence of end_sub instead of the last one, which is almost always what you want for this task.

Method 2: String Slicing (Simple for Unique Occurrences)

If you know your start and end substrings appear exactly once in each target document, basic string methods are a clean, efficient option:

origSent = 'This is the sentence I am intending to edit'
start_sub = 'the'
end_sub = 'intending'

# Find the starting index of the substring to remove
start_idx = origSent.find(start_sub)
# Calculate the end index (add length of end_sub to include it in the removal)
end_idx = origSent.find(end_sub) + len(end_sub)

# Slice the original string to keep parts before start_idx and after end_idx
newSent = origSent[:start_idx] + origSent[end_idx:]

print(newSent)  # Output: 'This is to edit'

Quick Notes:

  • str.find() returns the index of the first occurrence of the substring. If either substring might be missing from some documents, add checks for -1 (the return value when a substring isn't found) to avoid errors.

Both methods will give you the desired result for your example. Use regex if you need flexibility across varied documents, and slicing for simple, predictable cases.

内容的提问来源于stack exchange,提问作者cookie1986

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:22:47