[Solved] How does Python iterate over a string? [duplicate]


The easiest way for me to think about this is to remember that the word ‘letter’ could easily be replaced with anything you want to call it, it’s just a placeholder.

To illustrate, let’s replace ‘letter’ in your loop with the name ‘Dave’.

for Dave in 'Python':
    print 'Current letter : ', Dave

There is no ‘Dave’ in the string Python. But this will still print out every letter in the string ‘Python’. That is because when you setup your loop to iterate over a string, as you’ve done here, you are telling python that whatever you want it to do, in this case ‘print’, needs to be done to every item in the string.

for stuff in 'my_string':
    do stuff to every letter in my_string

Also, since you’re new to StackExchange, welcome. Since there are so many questions to be answered, to save everyone time, it works best if you do a very thorough google search to find out if an answer exists before posting a question on here. I’m sure there are a lot of good resources out there that will help you understand these concepts! Best of luck.

1

solved How does Python iterate over a string? [duplicate]