0

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

4
Contributors
3
Replies
11
Views
8 Years
Discussion Span
Last Post by jlm699
0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.