In this article, we’ll explore different ways to iterate over the words in a string using Python.
Let's start with an example to iterate over words in a Python string:
s = "Learning Python is fun"
for word in s.split():
print(word)
Output
Learning Python is fun
Explanation: Split the string into words and loop through each word
Table of Content
Using split() to Separate Words
Python’s split() method allows us to split a string by whitespace and returns a list of words.
s = "Learning Python is fun"
words = s.split()
print(words)
Output
['Learning', 'Python', 'is', 'fun']
Explanation: Here, split() divides the string at each whitespace, resulting in a list of words.
Iterating Directly with for Loop
Once the string is split into words, we can iterate over each word using a for loop.
s = "Learning Python is fun"
for word in s.split():
print(word)
Output
Learning Python is fun
Explanation:
- s.split() returns ['Python', 'programming', 'is', 'powerful'].
- The for loop then iterates over this list, printing each word individually.
Using enumerate to Track Index
To keep track of the word position while iterating, we can use enumerate().
s = "Learning Python is fun"
for index, word in enumerate(s.split()):
print(f"Word {index + 1}: {word}")
Output
Word 1: Learning Word 2: Python Word 3: is Word 4: fun
Explanation: enumerate() provides a counter (index) with each iteration, which helps in keeping track of word positions.
Handling Extra Spaces and Empty Words
Sometimes strings may have extra spaces. split() handles this well.
s = " Learning Python is fun "
for word in s.split():
print(word)
Output
Learning Python is fun
Explanation: split() automatically removes extra spaces.