1

I have this bit of code:

corpus = "T1T2T3"

for character in corpus:
    if character == 'T':
        print character + corpus[corpus.index(character) + 1]

I would simply like to print all of the T's and the letters that follow. In this case, it should print T1 T2 T3 -- instead only T1 T1 T1 is being printed. Any idea what might be going wrong?

3 Answers 3

2

Include the index in your iteration using the enumerate function:

for index, character in enumerate(corpus):
    if character == 'T':
        print character + corpus[index + 1]

Alternately, you can use a regular expression to look for the pattern you want:

import re

for match in re.findall('T.', corpus): # a . in the regular expression pattern means "match any character"
    print match
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect task for regex
Thanks -- helped me out a lot!
1

When you do corpus.index(character) , it will always find the index of the first occurence of character , so it would always return 0.

You can instead use enumerate() to get the index as well when you iterate over the string. Example -

corpus = "T1T2T3"

for idx, character in enumerate(corpus):
    if character == 'T' and (idx + 1) < len(corpus):
        print character + corpus[idx + 1]

Comments

0

string.index gets you only the first occurrence of the character in the string. You can specify which occurrence number you want; you would have to maintain this.

Alternately, perhaps something like this is what you have in mind, stepping through by the index.

for char_pos in len(corpus):
    if corpus[char_pos] == 'T':
        print corpus[char_pos:char_pos+2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.