In C++, I could do:
for(int i = 0; i < str.length(); ++i)
std::cout << str[i] << std::endl;
How do I iterate over a string in Python?
-
even easier:
for c in "test": print c:-)
hasen j : AFter a while of python-ing, I'm really hating C++ (I'm stuck with it for a current university course!)zgoda : Smart-and-to-the-point answer. :) -
As Johannes pointed out,
for c in "string": #do something with cYou can iterate pretty much anything in python using the
for loopconstruct,for example,
open("file.txt")returns a file object (and opens the file), iterating over it iterates over lines in that filefor line in open(filename): # do something with lineIf 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
forloop 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 definesnext()) -
Strings are just "sequences" in python and, as such, can be iterated in loops, as Johannes pointed out.
-
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 += 1But then again, why do that when strings are inherently iterable?
for i in str: print i
0 comments:
Post a Comment