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?
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?
If you need access to the index as you iterate through the string, use
enumerate()
: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.
But then again, why do that when strings are inherently iterable?
If you would like to use a more functional approach to iterating over a string (perhaps to transform it somehow), you can split the string into characters, apply a function to each one, then join the resulting list of characters back into a string.
A string is inherently a list of characters, hence 'map' will iterate over the string - as second argument - applying the function - the first argument - to each one.
For example, here I use a simple lambda approach since all I want to do is a trivial modification to the character: here, to increment each character value:
or more generally:
where my_function takes a char value and returns a char value.
You can use formatted string literals (PEP498; Pyton 3.6+) with
print
and sequence unpacking andenumerate
:If printing
tuple
values are sufficient, there is no need for the generator expression:As Johannes pointed out,
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 fileIf 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 definesnext()
)See official documentation
Even easier: