What if we would like to process words one by one? Python provides us with a utility function
split()that splits the string into pieces and returns a list of those pieces:
sentence = 'He ran out of money, so he had to stop playing poker.' words = sentence.split() print(words) # ['He', 'ran', 'out', 'of', 'money,', 'so', 'he', 'had', 'to', 'stop', 'playing', 'poker.']
split()can also accept a parameter based on which it will split the sentence:
s = 'Item one, Item two, Item three' items = s.split(', ') print(items) # ['Item one', 'Item two', 'Item three']
In the last example, the items were divided by a comma and a space, so providing that to split hints it to split the sentence based on
', 'instead of any whitespace.
Note: By default
split()splits the string based on any whitespace (newline, space, tab, etc). If we provide it with some specific value say
'\n', it will split only by a newline.
Given a sentence, where the words are separated by a space, your task is to print the words one by one on separate lines.
Input Python is awesome! Output Python is awesome!