Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through a string word by word

Tags:

python

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 
like image 335
m0bi5 Avatar asked Aug 06 '15 01:08

m0bi5


People also ask

How can we iterate through individual words in a string JS?

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).

How do you separate words in a string loop in Python?

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.

How do you iterate through text in Python?

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.


2 Answers

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).

like image 192
Anand S Kumar Avatar answered Oct 08 '22 22:10

Anand S Kumar


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 
like image 37
Joe T. Boka Avatar answered Oct 08 '22 20:10

Joe T. Boka