有多种。以下是其中一些常用的方法:
例子:
def get_string_between_words(sentence, word1, word2):
start_index = sentence.index(word1) + len(word1)
end_index = sentence.index(word2)
return sentence[start_index:end_index].strip()
sentence = "This is a sample sentence to demonstrate the method."
word1 = "sample"
word2 = "method"
result = get_string_between_words(sentence, word1, word2)
print(result) # 输出: " sentence to demonstrate the "
例子:
import re
def get_string_between_words(sentence, word1, word2):
pattern = re.compile(rf"{word1}\s+(.*?)\s+{word2}")
match = re.search(pattern, sentence)
if match:
return match.group(1)
else:
return ""
sentence = "This is a sample sentence to demonstrate the method."
word1 = "sample"
word2 = "method"
result = get_string_between_words(sentence, word1, word2)
print(result) # 输出: "sentence to demonstrate the"
这些方法可以用于提取两个单词之间的有效字符串,并根据实际需求进行适当的调整和扩展。
领取专属 10元无门槛券
手把手带您无忧上云