Iterate over String in Python

In Python or other programming language, iterate over a string means accessing each of its characters of a string one by one.

Since a string is a sequence of characters, we can iterate or traverse each character of the string. This process is called traversing or iteration.

There are basically three ways to iterate over characters of a string in Python. They are:

  • Using for loop
  • Using while loop
  • Using enumerate() function

Let’s understand each way to iterate over a string with the help of examples.

Iterate over a String in Python


Example 1:

Let’s write a Python program in which we will iterate or traverse over each character of a string using for loop.

# Python program to iterate over characters of a string using for loop.
# Create a string.
str = 'Google'

# Iterating over characters of a string.
for i in str:
    print(i, end=' ')

print('\n')
str2 = 'Yahoo'
for i in str2:
    print(i)
Output:
      G o o g l e 

      Y
      a
      h
      o
      o

In this example program, we have used end= ‘ ‘ in the print() function. By default, the print() statement ends with a newline character (\n). The function of end parameter is to change default behavior of print() statement in Python.

The parameter end = ” ” in the print() function is to place a white space after each character of a string while iterating. Thus, the the print() function ends with white space, not a newline.

The for loop iterates over each character of a string and prints each letter on a separate line.


Let’s write a Python program in which we will iterate over the index of characters of a string using for loop.

Example 2:

# Python program to iterate over index of a string using for loop.
# Create a string.
str = 'Google'
len_str = len(str) # finding the length of string.

# Iterating over the index of a string.
for i in range(0, len_str):
    print(str[i], end=' ')
Output:
      G o o g l e 

Let us write a program in Python to iterate through each character of a string using while loop.

Example 3:

# Python program to iterate over index of a string using while loop.
# Create a string.
institute = 'Scientech Easy'
len_str = len(institute) # finding the length of string.

# Iterating over index of a string.
index = 0
while index < len_str:
    letter = institute[index]
    print(letter, end=" ")
    index = index + 1
Output:
      S c i e n t e c h   E a s y

Let’s write a program in Python to traverse over a string using enumerate() function.

Example 4:

# Python program to iterate over a string using enumerate() function.
# Create a string.
str = 'Instagram'
# Iterating over a string.
for i, v in enumerate(str):
    print(v, end=" ")
Output:
      I n s t a g r a m 


Example 5:

# Python program to traverse over a string using for loop.
# Create a string.
def main():
    language = "Python"
    index = 0
    print(f"In the string '{language}'")
    for each_ch in language:
        print(f"Character '{each_ch}' has an index value of '{index}'")
        index += 1
if __name__ == '__main__':
    main()
Output:
       In the string 'Python'
       Character 'P' has an index value of '0'
       Character 'y' has an index value of '1'
       Character 't' has an index value of '2'
       Character 'h' has an index value of '3'
       Character 'o' has an index value of '4'
       Character 'n' has an index value of '5'

In this example, we have created a string “Python” and assigned it in a variable named language. We have initialized the index variable with a value zero. We have used a for loop that make it easy to loop or iterate over each character of a string.

The index value is incremented by a value of one when each character traversed in the string. We have displayed each character of the string and its corresponding index value.

Iterating over Words in a String in Python


In Python, we can also traverse or iterate over each word of a string. A string can consists of several words separated by a white space. There are two methods to iterate over words of a string in Python. They are:

  • Using split() function
  • Using re.findall() function

Let’s understand each method for iterating over each word including space in a string in Python with the help of examples.


Let’s write a program in Python to iterate over each word of a string using split() function.

Example 6:

# Python program to traverse over words of a string using split() function.
# Create a string.
def main():
    str = "Python is an easy to use programming language."
    index = 0
    print(f"In the string '{str}'")
 
# Call split() function to extract words from string.
    result = str.split()
    print('\nWords of string are as:')
    for each_word in result:
        print(each_word)
        index += 1
if __name__ == '__main__':
    main()
Output:
      In the string 'Python is an easy to use programming language.'

      Words of string are as:
      Python
      is
      an
      easy
      to
      use
      programming
      language.

In this example, we have used split() function to traverse over each word a string. This function splits the string into a list of words, but it fails if a string contains punctuation marks, such as question mark, exclamation point, comma, colon, semicolon, etc. To overcome this issue, use re.findall() function.


Let’s write a program to iterate over each word of a string using re.findall() function.

Example 7:

# Python program to traverse over words of a string using findall() function.
import re
def main():
    str = "I love Python programming."
    index = 0
    print(f"In the string '{str}'")
 
# Call split() function to extract words from string.
    result = re.findall(r'\w+',str)
    print('\nWords of string are as:')
    for each_word in result:
        print(each_word)
        index += 1
if __name__ == '__main__':
    main()
Output:
      In the string 'I love Python programming.'

     Words of string are as:
     I
     love
     Python
     programming

As you can see in the output, the re,findall() function iterate over the words of the string while ignoring punctuation marks.


In this tutorial, you have learned about how to iterate over each character of a string in Python with the help of some examples. I hope that you will have understood the basic concepts of iterating over string and practiced all example programs.
Thanks for reading!!!