I was wondering if there was any way to make a for loop go through a string word by word, rather then character by character. For example,

for letter in "Hello world"
print letter


it would print out
H
e
l
l
o

etc.

I was wondering if I could make it so that it would instead print out like

Hello
World

Any help would be greatly appreciated!

Recommended Answers

All 4 Replies

You can split the string into a list of words at a whitespace (space, spaces, tab, newline) ...

# convert a string to a list of words

str1 = 'You never find a missing item until you replace it'
print "Original string:"
print str1
# split the string into a list of words at a whitespace
wordList = str1.split(None)
print "String split into a list of words:"
print wordList
print
# now print out each word in the list on a separate line
for word in wordList:
    print word

I was trying to figure out a way to do it manually(without the split method). I feel like I am always trying to reinvent the wheel.

A good part of the fun of programming in Python is the ease with which you can experiment with the code. So go ahead and reinvent a better wheel!

Ahhhh thanks very much :mrgreen:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.