如何在Python中替换或删除两个指定子串及其间的内容
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 ofend_subinstead 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

