Iterating each character in a string using Python
Solution 1
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()
)
Solution 2
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
Solution 3
Even easier:
for c in "test":
print c
Solution 4
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
Solution 5
Well you can also do something interesting like this and do your job by using for loop
#suppose you have variable name
name = "Mr.Suryaa"
for index in range ( len ( name ) ):
print ( name[index] ) #just like c and c++
Answer is
M r . S u r y a a
However since range() create a list of the values which is sequence thus you can directly use the name
for e in name:
print(e)
This also produces the same result and also looks better and works with any sequence like list, tuple, and dictionary.
We have used tow Built in Functions ( BIFs in Python Community )
1) range() - range() BIF is used to create indexes Example
for i in range ( 5 ) :
can produce 0 , 1 , 2 , 3 , 4
2) len() - len() BIF is used to find out the length of given string
Paradius
Updated on January 11, 2021Comments
-
Paradius over 3 years
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?
-
aiham about 13 yearsInstead of your first while loop, you can do: for i in range(len(str)): print(str[i]) Which in my opinion is better than having to manage the counter on your own. Even better is marcog's answer using enumerate.
-
Akseli Palén almost 12 yearsAs a note, reversed iteration is archived with: for c in reversed("string")
-
gkimsey about 11 yearsThis may be based on just having used C for so long, but I almost always end up using this C-ish method. For instance, I have a file with some 4-digit numbers scattered about, all of which start with 0. So I need to find a "0" and grab it and the next 3 characters, and move on without duplicating the number if there's another 0 following it. None of the "for c in str" or "for i,c in enumerate(str)" methods work because I need control of the index. I'm sure a regular expression would be much better, though.
-
Mauro Vanetti over 9 yearsI'm a newbie in Python. For some reason, this doesn't compile in my environment, and I had to put c in brackets to make it work:
for c in "test": print (c)
Why? -
Johannes Weiss over 9 years@MauroVanetti that's almost certainly because you're using Python 3 and when I answered the question there was AFAIK only Python 2.
-
izak almost 8 years
for i in range(len(...))
is evil. In python 2.x,range()
creates a list, so for a very long length you may end up allocating a very large block of memory. At the very least usexrange()
in those cases. Also, repeated indexing of the same string is much slower than iterating directly over the string. If you need the index, useenumerate()
. -
winklerrr about 7 yearsFrom which part of the documentation do you know that a string is a iterator type?
-
shadow0359 about 7 yearsdir() a string..you with see iter attribute.
-
Messa about 7 yearsPro tip: it starts from zero. If you need to start it from one:
1 t
,2 e
,3 s
,4 t
use the parameter "start":for i, c in enumerate('test', start=1)
-
Sam Mason over 4 yearsnote that this only applies to Python 2 which is hopefully a shrinking minority now