I wanted to know how to iterate through a string word by word.
string = "this is a string" for word in string: print (word)
The above gives an output:
t h i s i s a s t r i n g
But I am looking for the following output:
this is a string
Simple for loop can use for in iterate through words in a string JavaScript. And for iterate words in string use split, map, and join methods (functions).
Given a String comprising of many words separated by space, write a Python program to iterate over these words of the string. Using split() function, we can split the string into a list of words and is the most generic and recommended method if one wished to accomplish this particular task.
You can traverse a string as a substring by using the Python slice operator ([]). It cuts off a substring from the original string and thus allows to iterate over it partially. To use this method, provide the starting and ending indices along with a step value and then traverse the string.
When you do -
for word in string:
You are not iterating through the words in the string, you are iterating through the characters in the string. To iterate through the words, you would first need to split the string into words , using str.split()
, and then iterate through that . Example -
my_string = "this is a string" for word in my_string.split(): print (word)
Please note, str.split()
, without passing any arguments splits by all whitespaces (space, multiple spaces, tab, newlines, etc).
This is one way to do it:
string = "this is a string" ssplit = string.split() for word in ssplit: print (word)
Output:
this is a string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With