首页 > 解决方案 > 如何从字符串中查找子字符串的开始和结束索引

问题描述

我正在尝试获取子字符串的开始和结束位置

mystr = "I live at 2 Inchydoney Island. Inchydoney, Co Cork"
search_str = '2 Inchydoney Island. Inchydoney, Co Cork'

result = [i+1 for i,w in enumerate(mystr.split()) if w.lower() == search_str]
print(result)  

我尝试了一段代码,但它没有返回任何内容。

预期产出

[11,48]

标签: pythonstringindexing

解决方案


您可以使用indexfind来查找较长字符串中子字符串的位置。

mystr = "I live at 2 Inchydoney Island. Inchydoney, Co Cork"
search_str = '2 Inchydoney Island. Inchydoney, Co Cork'
start = mystr.index(search_str)
end = start + len(search_str)

推荐阅读