589

How can I iterate over a string in Python (get each character from the string, one at a time, each time through a loop)?

0

9 Answers 9

525

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

3
  • 20
    As a note, reversed iteration is archived with: for c in reversed("string") Commented Jul 12, 2012 at 23:05
  • From which part of the documentation do you know that a string is a iterator type?
    – winklerrr
    Commented Mar 1, 2017 at 9:45
  • dir() a string..you with see iter attribute.
    – ns15
    Commented Apr 10, 2017 at 14:23
348

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

for index, character in enumerate('test'):
    print(index, character)
... 
0 t
1 e
2 s
3 t
1
  • 15
    Pro 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)
    – Messa
    Commented Apr 21, 2017 at 17:45
96

Even easier:

for c in "test":
    print c
2
  • 2
    I'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? Commented Sep 3, 2014 at 10:35
  • 14
    @MauroVanetti that's almost certainly because you're using Python 3 and when I answered the question there was AFAIK only Python 2. Commented Sep 3, 2014 at 10:38
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
3
  • 7
    Instead 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.
    – aiham
    Commented Apr 13, 2011 at 6:39
  • 1
    This 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.
    – gkimsey
    Commented Mar 13, 2013 at 15:22
  • 1
    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 use xrange() in those cases. Also, repeated indexing of the same string is much slower than iterating directly over the string. If you need the index, use enumerate().
    – izak
    Commented Jun 7, 2016 at 7:49
7

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

6

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:

>>> ''.join(map(lambda x: chr(ord(x)+1), "HAL"))
'IBM'

or more generally:

>>> ''.join(map(my_function, my_string))

where my_function takes a char value and returns a char value.

3

Several answers here use range. xrange is generally better as it returns a generator, rather than a fully-instantiated list. Where memory and or iterables of widely-varying lengths can be an issue, xrange is superior.

1
  • 2
    note that this only applies to Python 2 which is hopefully a shrinking minority now
    – Sam Mason
    Commented Nov 11, 2019 at 13:56
2

You can also do the following:

txt = "Hello World!"
print (*txt, sep='\n')

This does not use loops but internally print statement takes care of it.

* unpacks the string into a list and sends it to the print statement

sep='\n' will ensure that the next char is printed on a new line

The output will be:

H
e
l
l
o
 
W
o
r
l
d
!

If you do need a loop statement, then as others have mentioned, you can use a for loop like this:

for x in txt: print (x)
0

If you ever run in a situation where you need to get the next char of the word using __next__(), remember to create a string_iterator and iterate over it and not the original string (it does not have the __next__() method)

In this example, when I find a char = [ I keep looking into the next word while I don't find ], so I need to use __next__

here a for loop over the string wouldn't help

myString = "'string' 4 '['RP0', 'LC0']' '[3, 4]' '[3, '4']'"
processedInput = ""
word_iterator = myString.__iter__()
for idx, char in enumerate(word_iterator):
    if char == "'":
        continue

    processedInput+=char

    if char == '[':
        next_char=word_iterator.__next__()
        while(next_char != "]"):
          processedInput+=next_char
          next_char=word_iterator.__next__()
        else:
          processedInput+=next_char

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.