Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

Find and print the indexes of a substring in string that starts and ends with a specific character in python

Good day everyone!

Lets say I have a string such as:

seq = 'ggtctgaatcgggtcaattggcccgctgagggtcaagtaccgggtgacatttgagcatgagtagatcgaggstggccagtatgcaaacggccgattgacgttaaggctaagcctaaaggtccacaggtcagtccagttagcattcgagtctaacggtatcggatctatttcggaaaaggctcatacgcgatcatgcggtccagagcgtac'

In this string, I have a certain sequence (substring) that starts and ends with atgca:

'atgca......atgca' # there can be any letters in between them

How can I print the indexes of atgca? I want to print the index of atgca in which it appears at the beginning of the substring i've given above, and also the index of atgca in which it appears at the end of the substring.

Any help is appreciated!

question from:https://stackoverflow.com/questions/65936377/find-and-print-the-indexes-of-a-substring-in-string-that-starts-and-ends-with-a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Can you modify the above code to just check for the beginning and end each time you loop. I also added a not index1 and not index2 because you need to address what happens if find returns 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

Now that you have the two indexes you could even print the portion of the string that lies between if you wanted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...