Hey everybody im a real newbee at python and im just wondering how to split a string of words into pieces and print on separate lines for example:

" sun is shining"
to:

sun
is
shining


i know this might be a simple task for a lot of people but i would appreciate any help that i can get. THANX
//OBOL

Recommended Answers

All 3 Replies

for word in 'sun is shining'.split(' '):
    print word
Member Avatar for leegeorg07

i was wondering, couldnt you use lambda?

how to split a string of words into pieces

Use the split() method like so:

>>> my_phrase = "the sun is shining"
>>> my_phrase.split()
['the', 'sun', 'is', 'shining']
>>>

and print on separate lines

As you can see from above, split() returns a list containing each word as an element. I'm going to store this list and then iterate over it with a for loop. On each iteration the value of each_word will update with the next element from my_split_words . Refer to the following:

>>> my_split_words = my_phrase.split()
>>> for each_word in my_split_words:
...     print each_word
...     
the
sun
is
shining
>>>

I hope that clears up what each step does. Please let us know if you need anything explained further.

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.