How do I iterate over the words of a string?

 

To iterate over the words of a string in Python, you can split the string into words using the split() method or regular expressions and then iterate through the resulting list. Here's an example using both methods:

Using split() method:

python
# Input string text = "Hello, this is a sample sentence." # Split the string into words using whitespace as the delimiter words = text.split() # Iterate over the words for word in words: print(word)

In this example, we split the input string text into words by calling text.split(). By default, split() uses whitespace as the delimiter and returns a list of words. We then iterate over the words using a for loop and print each word.

Using regular expressions (with re module):

python
import re # Input string text = "Hello, this is a sample sentence." # Use a regular expression to find words word_pattern = r'\b\w+\b' words = re.findall(word_pattern, text) # Iterate over the words for word in words: print(word)

In this example, we use the re module to find words in the input string. The regular expression r'\b\w+\b' matches one or more word characters surrounded by word boundaries. The re.findall() function returns a list of all matching words. We then iterate over these words and print each one.

Both methods allow you to iterate over the words of a string in Python, and you can choose the one that best suits your specific requirements and input data.

Comments