繁体   English   中英

如何从字符串中查找子字符串的开始和结束索引

[英]How to find start & end index of a sub-string from a string

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

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]

您可以使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM