![]() |
VOOZH | about |
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:
Learning Python is fun
Explanation: Split the string into words and loop through each word
Table of Content
Python’s split() method allows us to split a string by whitespace and returns a list of words.
['Learning', 'Python', 'is', 'fun']
Explanation: Here, split() divides the string at each whitespace, resulting in a list of words.
Once the string is split into words, we can iterate over each word using a for loop.
Learning Python is fun
Explanation:
To keep track of the word position while iterating, we can use enumerate().
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.
Sometimes strings may have extra spaces. split() handles this well.
Learning Python is fun
Explanation: split() automatically removes extra spaces.