Python3:求一个字符串的两个子串之间的长度

Python3: Find length between two substrings of a string

我有两个小序列,我在“长字符串”中搜索它们。如果两个序列都找到了,则将“长字符串”的键附加到一个列表中(我搜索IN的字符串是一个字典值)。

现在我正在寻找一种方法,acquire/calculate 两个子字符串之间的距离(如果找到的话)。

因此,例如:

String: ABCDEFGHIJKL
sequence1: ABC
sequence2: JKL

我想获取 DEFGHI 的长度,即 6。

这是我用于查找子字符串的代码,其中包含一些我想要的“伪代码”想法(变量开始和结束)。此代码不起作用 (ofc)

def search (myDict, list1, list2):
    # initialize empty list to store found keys
    a=[]
    # iterating through dictionary
    for key, value in myDict.items():
        # if -35nt motif is found between -40 and -20
        for item in thirtyFive:
            if item in value[60:80]:
                start=myDict[:item]
            # it is checked for the -10nt motif from -40 to end
                for item in ten:
                    if item in value[80:]:
                        end=myDict[:item]
                # if both conditions are true, the IDs are
                # appended to the list
                        a.append(key)
    distance=start-end
    return a, distance

第二个想法: 到目前为止,我发现了一些关于如何在两个子字符串之间获取字符串的内容。所以,接下来我能想到的是,获取序列并执行类似 len(sequence) 的操作。

所以,我想知道,如果我的第一个想法,在我找到小序列的同时以某种方式做到这一点,是否有可能,并且我的第二个想法是否朝着正确的方向思考。

提前致谢:)

@Carlos 使用str.find 方法

后的解决方案
def search (myDict, list1, list2):
    # initialize empty list to store found keys
    a=[]
    # iterating through dictionary
    for key, value in myDict.items():
        # if -35nt motif is found between -40 and -20
        for item in thirtyFive:
            if item in value[60:80]:
                start=value.find(item)
            # it is checked for the -10nt motif from -20 to end
                for item in ten:
                    if item in value[80:]:
                        end=value.find(item)
                # if both conditions are true, the IDs are
                # appended to the list
                        a.append(key)
                        search.distance=end-start-len(item)

    return a

# calling search function
x=search(d,thirtyFive,ten)
#some other things I need to print
y=len(x)
print(str(x))
print(y)
# desired output
print(search.distance)

使用str.find()得到两个索引,并调整第一个索引的长度。

也不要忘记极端情况,例如子串重叠的地方。

检查这个

In [1]: a='ABCDEFGHIJKL'

In [2]: b='ABC'

In [3]: c='JKL'

In [4]: a.find(b)
Out[4]: 0

In [6]: a.find(c)
Out[6]: 9

In [7]: l=a.find(b) + len(b)

In [8]: l
Out[8]: 3

In [10]: a[l:a.find(c)]
Out[10]: 'DEFGHI'

In [11]: 

您也可以使用正则表达式来完成:

import re
s = "ABCDEFGHIJKL"
seq1 = "ABC"
seq2 = "JKL"

s1 = re.match(seq1 + "(.*)" + seq2, s).group(1)
print s1
print(len(s1))

输出

DEFGHI
6

使用str.replace

s2 = s.replace(seq1, '').replace(seq2, '')
print s2
print(len(s2))

输出

DEFGHI
6

现场演示here

使用正则表达式的解决方案:

import re

string = "ABCDEFGHIJKL"
sequence1 = "ABC"
sequence2 = "JKL"

result = re.search(sequence1+'(.*)'+sequence2,string)
print(len(result.group(1)))