Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: iterate through string but need to know index of current character

I’m iterating through a string and need to perform certain actions if the index number of a given character equals a certain value. However I’m not sure of the best way of keeping track of the current index number during the iteration. For example I need code that broadly does the following:

def myfunc(word):
    for n in word:
        if n[index] = 0:
            do this
        elif n[index] = 4:
            do this
        else:
            do this

I just can’t seem to find any inbuilt counter or function that allows me to keep track of the current iteration index. I could add a counter in as variable and just +1 after each loop but this seems clunky and I would have thought Python would know the current iteration number of "n" and could report it back?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Two ways to do this. Iterate the index i between 0 and the len of the str:

for i in range(len(word)):
  c = word[i]

Or use python’s enumerate function to do both at once:

for i, c in enumerate(word):
  ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading