[英]Find and print the indexes of a substring in string that starts and ends with a specific character in python
今天是个好日子!
可以说我有一个字符串,例如:
seq = 'ggtctgaatcgggtcaattggcccgctgagggtcaagtaccgggtgacatttgagcatgagtagatcgaggstggccagtatgcaaacggccgattgacgttaaggctaagcctaaaggtccacaggtcagtccagttagcattcgagtctaacggtatcggatctatttcggaaaaggctcatacgcgatcatgcggtccagagcgtac'
在这个字符串中,我有一个以atgca开头和结尾的特定序列(子字符串):
'atgca......atgca' # there can be any letters in between them
如何打印atgca的索引? 我想打印出现在上面给出的 substring 开头的 atgca 索引,以及出现在 substring 结尾的 atgca 索引。
任何帮助表示赞赏!
内置的“查找”function 正是这样做的:
start = 0
while start < len(seq):
index = seq.find('atgca', start)
if index == -1:
break
print index
start = index + 1
你能修改上面的代码,每次循环时只检查开始和结束吗? 我还添加了一个 not index1 和 not index2,因为您需要解决如果 find 返回 None 会发生什么。
start = 0
while start < len(seq):
index1 = seq.find('atgca', start)
if index1 == -1 or not index1:
break
start = index1
index2 = seq.find('atgca',start)
if not index2:
break
print index1, index2
start = index2 + 1
现在您有了两个索引,如果需要,您甚至可以打印位于两者之间的字符串部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.