573

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

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Paradius
  • 7,949
  • 11
  • 32
  • 38

9 Answers9

507

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

vallentin
  • 23,478
  • 6
  • 59
  • 81
hasen
  • 161,647
  • 65
  • 194
  • 231
344

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
moinudin
  • 134,091
  • 45
  • 190
  • 216
  • 13
    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 Apr 21 '17 at 17:45
94

Even easier:

for c in "test":
    print c
Johannes Weiss
  • 52,533
  • 16
  • 102
  • 136
  • 1
    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? – Mauro Vanetti Sep 03 '14 at 10:35
  • 12
    @MauroVanetti that's almost certainly because you're using Python 3 and when I answered the question there was AFAIK only Python 2. – Johannes Weiss Sep 03 '14 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
Andrew Szeto
  • 1,199
  • 1
  • 9
  • 13
  • 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 Apr 13 '11 at 06: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 Mar 13 '13 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 Jun 07 '16 at 07: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

Mr. Suryaa Jha
  • 1,516
  • 16
  • 10
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.

MikeW
  • 5,504
  • 1
  • 34
  • 29
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.

N6151H
  • 150
  • 1
  • 11
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)
Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33
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