如何在Python中查找子字符串的开始索引和结束索引[关闭]

问题描述 投票:-1回答:3
我有一个字符串:

a = "Hello how are you" b ="how"

我想在a中搜索b,结果将显示a中b的开始索引和结束索引。

答案:

start_index = 7 end_index = 9

任何人都可以帮助我。 
python string substring
3个回答
0
投票
使用str.find

start_index = a.find(b) + 1 end_index = a.find(b) + len(b)


0
投票
您可以使用正则表达式并访问匹配项的span

import re substring = re.search(b,a) start, end = substring.span()


0
投票
您可以使用正则表达式模块执行此操作:

import re a = "Hello how are you" b ="how" start_index, end_index = re.search(b, a).span() print(start_index, end_index)

© www.soinside.com 2019 - 2024. All rights reserved.