簡體   English   中英

如何在字符串中找到模式最后一次出現的位置,並使用這些位置從另一個字符串中提取子字符串

[英]How to find positions of the last occurrence of a pattern in a string, and use these to extract a substring from another string

我需要一些特定問題的幫助,我似乎在本網站上找不到。 我有一個看起來像這樣的結果:

result = "ooooooooooooooooooooooMMMMMMooooooooooooooooooMMMMMMooooooooooMMMMMMMMoo"

這是跨膜預測。 所以對於這個字符串,我有另一個相同長度的字符串,但是是一個氨基酸代碼,例如:

amino_acid_code = "MSDENKSTPIVKASDITDKLKEDILTISKDALDKNTWHVIVGKNFGSYVTHEKGHFVYFYIGPLAFLVFKTA"

我想對最后一個“M”區做一些研究。 這可以在長度上有所不同,以及后面的“o”。 所以在這種情況下,我需要從最后一個字符串中提取“PLAFLVFK”,它對應於最后一個“M”區域。

我已經有了這樣的東西,但我無法弄清楚如何獲得開始位置,而且我也相信一個更簡單(或計算上更好)的解決方案是可能的。

end = result.rfind('M')
start = ?
region_I_need = amino_acid_code[start:end]

提前致謝

要同時找到起始位置, rfind在切掉result字符串末尾的字符后再次使用rfind

result = "ooooooooooooooooooooooMMMMMMooooooooooooooooooMMMMMMooooooooooMMMMMMMMoo"
amino_acid_code = "MSDENKSTPIVKASDITDKLKEDILTISKDALDKNTWHVIVGKNFGSYVTHEKGHFVYFYIGPLAFLVFKTA"

# add 1 to the indices to get the correct positions
end = result.rfind('M') + 1
start = result[:end].rfind('o') + 1
region_I_need = amino_acid_code[start:end]

print(start, end)
print(amino_acid_code[start:end])
>>> 62 70
>>> PLAFLVFK

暫無
暫無

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

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