Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找具有重叠字符的两个子字符串的索引_Python_String_Find_Substring - Fatal编程技术网

Python 查找具有重叠字符的两个子字符串的索引

Python 查找具有重叠字符的两个子字符串的索引,python,string,find,substring,Python,String,Find,Substring,我想在如下给定的字符串中找到两个子字符串的索引: find_start = '1L' find_end = 'L' >>> blah = 'A1LELST5W' >>> blah.index('1L') 1 >>> blah.index('L') 2 # i want it to give me 4 如果我使用index方法,它会给出字符串中第三个字符的“L”。但我希望它将“1L”和“L”作为单独的字符串,并给我第五个字符 有没有一个简单

我想在如下给定的字符串中找到两个子字符串的索引:

find_start = '1L'
find_end = 'L'
>>> blah = 'A1LELST5W'
>>> blah.index('1L')
1
>>> blah.index('L')
2  # i want it to give me 4
如果我使用index方法,它会给出字符串中第三个字符的“L”。但我希望它将“1L”和“L”作为单独的字符串,并给我第五个字符

有没有一个简单的方法可以做到这一点?或者我必须将除了
find_start
之外的所有内容存储在一个新字符串中,然后尝试通过该字符串进行索引?(但这会弄乱字符串中所有内容的位置)。

该方法具有开始和结束参数,允许您约束搜索。因此,您只需在第一个搜索结束的位置开始第二个搜索:

>>> find_start = '1L'
>>> find_end = 'L'
>>> blah = 'A1LELST5W'
>>> first = blah.index('1L')
>>> first
1
>>> blah.index('L', first + len(find_start))
4

为什么
1L
不是真正的
L
,而
EL
是?
blah
是一个带值的字符串,
1L
是一个大小为2的字符串。由于您希望在字符串
blah
中查找字母
L
的索引,因此
index
将为您提供第一次出现的索引号。因此,
索引
被赋予位置2,因为它在索引2处遇到了
L