How to iterate over words of String in Python?

Python – Iterate Over Words of String

To iterate over words of a string,

  • Split the string. The common delimiter between words in a string is space. The split returns an array. Each element in the array is a word.
  • Use for loop to iterate over the words present in the array.

Examples

1. Iterate over words in given string

In this example, we will iterate over the words of a string and print them one by one.

Python Program

str = 'Hello! I am Robot. This is a Python example.'

# Split string
splits = str.split()

# For loop to iterate over words array
for split in splits:
    print(split)
Run Code Copy

Output

Python - Iterate Over Words of String

2. Clean given string and iterate over the words

In this example, we will clean the string and remove anything other than alphabets and spaces. Then we split the string and iterate over the words.

Python Program

import re

str = 'Hello! I am Robot. This is a Python example.'

# Clean string
pat = re.compile(r'[^a-zA-Z ]+')
str = re.sub(pat, '', str).lower()

# Split string
splits = str.split()

# For loop to iterate over words array
for split in splits:
    print(split)
Run Code Copy

Output

Python - Iterate Over Words of String

Summary

In this tutorial of Python Examples, we learned how to iterate over the words of given string.

Related Tutorials

Code copied to clipboard successfully 👍