簡體   English   中英

Python3:查找字符串的兩個子字符串之間的長度

[英]Python3: Find length between two substrings of a string

我有兩個小序列,它們以“長字符串”搜索。 如果找到兩個序列,則將“長字符串”的關鍵字附加到列表中(我搜索的字符串是字典值)。

現在,我正在尋找一種方法來獲取/計算兩個子字符串之間的距離(如果找到)。

因此,例如:

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)的操作。

因此,我想知道,如果我的第一個主意是在找到小序列時以某種方式進行操作,是否有可能,並且如果我以第二個主意朝着正確的方向思考。

提前致謝 :)

使用str.find方法在@Carlos之后的解決方案

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

您也可以使用regex來做到這一點:

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

現場演示在這里

使用str.find()獲得兩個索引,並調整第一個索引的長度。

也不要忘記在極端情況下,例如子字符串重疊。

使用正則表達式的解決方案:

import re

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM