Skip to main content
 首页 » 编程设计

python 3 : Find length between two substrings of a string

2025年05月04日12bjzhanghao

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

现在我正在寻找一种方法来获取/计算两个子字符串之间的距离(如果找到的话)。

所以,例如:

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) 

请您参考如下方法:

检查这个

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]: