lex
lex

Reputation: 173

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!

Upvotes: 2

Views: 629

Answers (2)

Rasputin
Rasputin

Reputation: 181

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.

Upvotes: 1

Farkash
Farkash

Reputation: 17

The builtin 'find' function does exactly that:

start = 0
while start < len(seq):
    index = seq.find('atgca', start)
    if index == -1:
        break
    print index
    start = index + 1

Upvotes: 1

Related Questions