繁体   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