Fix Python – Iterating each character in a string using Python


Asked By – Paradius

In C++, I can iterate over an std::string like this:

std::string str = "Hello World!";

for (int i = 0; i < str.length(); ++i)
    std::cout << str[i] << std::endl;

How do I iterate over a string in Python?

Now we will see solution for issue: Iterating each character in a string using Python


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

This question is answered By – hasen

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0