Iterating each character in a string using Python

The Question :

528 people think this question is useful

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?

The Question Comments :

The Answer 1

459 people think this answer is useful

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

The Answer 2

319 people think this answer is useful

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

The Answer 3

91 people think this answer is useful

Even easier:

for c in "test":
    print c

The Answer 4

39 people think this answer is useful

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

The Answer 5

7 people think this answer is useful

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

The Answer 6

4 people think this answer is useful

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.

The Answer 7

2 people think this answer is useful

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.

The Answer 8

0 people think this answer is useful

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

The Answer 9

0 people think this answer is useful

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)

The Answer 10

0 people think this answer is useful

We have Multiple Ways to Iterating each character in a string using Python.

The following are various ways to iterate the chars in a Python string. Let’s first begin with the for loop method. It is the most prominent and straightforward technique to iterate strings. sample code:

string_to_iterate = "Hello World!"
for char in string_to_iterate:
  print(char)

The Output is as below:-

H
e
l
l
o
 
W
o
r
l
d
!

Another quite simple way to traverse the string is by using Python range function. This method lets us access string elements using the index.

#Python Program: Python range to iterate over a string
#Using range() to iterate over a string in Python
string_to_iterate = "Hello World!"
for char_index in range(len(string_to_iterate)):
   print(string_to_iterate[char_index])

The Output is as below:-

H
e
l
l
o
 
W
o
r
l
d
!

We can traverse a string as a substring by using the Python slice operator ([]). It cuts off a substring from the original string and thus allows to iterate over it partially. The [] operator has the following syntax:

# Slicing Operator
string [starting index : ending index : step value]

To use this method, we provide the starting and ending indices along with a step value and then traverse the string. Below is the example code that iterates over the first six letters of a string.

#Python Program: Slice operator to iterate strings partially
#Using slice [] operator to iterate over a string partially  
string_to_iterate = "Hello World!"
for char in string_to_iterate[0 : 10 : 1]:
   print(char)

Following is the Output:-

H
e
l
l
o
 
W
o
r
l

We can also do Slice operator first generates a reversed string, and then we use the for loop to traverse it. Instead of doing it, we can use the indexing to iterate strings backward.

#Python Program: Using indexing to iterate strings backward
#Using indexing to iterate string backward

string_to_iterate = "Hello World!"
char_index = len(string_to_iterate) - 1
while char_index >= 0:
   print(string_to_iterate[char_index])
   char_index -= 1

The Following is the Output of reverse string:-

!
d
l
r
o
W
 
o
l
l
e
H

Let’s now consolidate all examples inside the Main() function and execute from there. From the Below Example Hope We will solve all the possible solutions of iterate each character in a string:-

#Program:
#Here are some Python Program to iterate strings char by char

def Main():
   print("First way to iterate string in python")
   string_to_iterate = "Hello World!"
   for char in string_to_iterate:
      print(char)

   print("\nSecond way to iterate string in python")
   string_to_iterate = "Hello World!"
   for char_index in range(len(string_to_iterate)):
      print(string_to_iterate[char_index])
   
   print("\nThird way to iterate string in python")
   string_to_iterate = "Hello Python World!"
   for char in string_to_iterate[0 : 9 : 1]:
      print(char)
 
   print("\nFourth way to iterate string in python")
   string_to_iterate = "Hello_Python_World!"
   for char in string_to_iterate[ :  : 2]:
      print(char)
   
   print("\nFifth way to iterate string in python")
   string_to_iterate = "Hello World!"
   for char in string_to_iterate[ :  : -1]:
      print(char)
   
   print("\nSixth way to iterate string in python")
   string_to_iterate = "Hello World!"
   char_index = len(string_to_iterate) - 1
   while char_index >= 0:
      print(string_to_iterate[char_index])
      char_index -= 1
   
   print("\nSeventh way to iterate string in python")
   string_to_iterate = "Hello World!"
   char_index = 1
   while char_index <= len(string_to_iterate):
      print(string_to_iterate[-char_index])
      char_index += 1
   
if __name__ == "__main__":
    Main()

The Output is following:-

First way to iterate string in python
H
e
l
l
o
 
W
o
r
l
d
!

Second way to iterate string in python
H
e
l
l
o
 
W
o
r
l
d
!

Third way to iterate string in python
H
e
l
l
o
 
P
y
t

Fourth way to iterate string in python
H
l
o
P
t
o
_
o
l
!

Fifth way to iterate string in python
!
d
l
r
o
W
 
o
l
l
e
H

Sixth way to iterate string in python
!
d
l
r
o
W
 
o
l
l
e
H

Seventh way to iterate string in python
!
d
l
r
o
W
 
o
l
l
e
H

I will try to maximum number of ways to iterate each character in a string in Python.

Add a Comment