The Python Oracle

Iterating each character in a string using Python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC I Beethoven Sonata No 31 in A Flat M

--

Chapters
00:00 Question
00:21 Accepted answer (Score 498)
01:29 Answer 2 (Score 341)
01:45 Answer 3 (Score 94)
01:56 Answer 4 (Score 40)
02:23 Thank you

--

Full question
https://stackoverflow.com/questions/5383...

Accepted answer links:
[See official documentation]: http://docs.python.org/library/stdtypes....

Answer 2 links:
[enumerate()]: http://docs.python.org/library/functions...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #iteration

#avk47



ACCEPTED ANSWER

Score 518


As Johannes pointed out,

for c in "string":
    #do something with c

You can iterate pretty much anything in python using the for loop construct,

for example, open("file.txt") returns a file object (and opens the file), iterating over it iterates over lines in that file

with open(filename) as f:
    for line in f:
        # do something with line

If that seems like magic, well it kinda is, but the idea behind it is really simple.

There's a simple iterator protocol that can be applied to any kind of object to make the for loop work on it.

Simply implement an iterator that defines a next() method, and implement an __iter__ method on a class to make it iterable. (the __iter__ of course, should return an iterator object, that is, an object that defines next())

See official documentation




ANSWER 2

Score 347


If you need access to the index as you iterate through the string, use enumerate():

>>> for i, c in enumerate('test'):
...     print i, c
... 
0 t
1 e
2 s
3 t



ANSWER 3

Score 95


Even easier:

for c in "test":
    print c



ANSWER 4

Score 40


Just to make a more comprehensive answer, the C way of iterating over a string can apply in Python, if you really wanna force a square peg into a round hole.

i = 0
while i < len(str):
    print str[i]
    i += 1

But then again, why do that when strings are inherently iterable?

for i in str:
    print i