vmpfc1
vmpfc1

Reputation: 63

Printing Next Item in Python For Loop

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?

Upvotes: 1

Views: 82

Answers (3)

Prune
Prune

Reputation: 77847

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]

Upvotes: 0

Anand S Kumar
Anand S Kumar

Reputation: 90899

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]

Upvotes: 1

nneonneo
nneonneo

Reputation: 179422

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

Upvotes: 2

Related Questions