How to iterate over words of String in Python?

Python – Iterate Over Words of String

To iterate over words of a string,

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

Output

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

Output

Summary

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

Related Tutorials

Privacy Policy Terms of Use

SitemapContact Us