I am trying to print a string one word per line using a loop. For example if the string is, 'I need practice', the string should print: I'\n' need'\n' practice

My code so far looks like this:

phrase=input('enter a phrase: ') for char in phrase: print (char, end ='') if char == '': print('\n') 

However, my output looks like this:

I need practice

1

2 Answers

You can use the .split() function to split a string by spaces and that will give you back a list of words that you can then loop and print them out.

The function accepts a string that will be used as the delimiter (e.g ",") if this argument is not specified or is None it will run an algorithm that will consider a sequence of whitespaces as a single separator and hence, as a result, no matter how many spaces there are between the words you will get a list of words with no whitespaces at the start or the end of each substring.

phrase = input("Enter a phrase: ") words = phrase.split() # ['I', 'need', 'practice'] for word in words: print(word) 

Just replace the spaces with \n 's

phrase=input('enter a phrase: ')

words = phrase.replace(' ', '\n')

Note the space in the first argument of replace.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy