Home > Back-end >  how do i print an input but remove one word per line?
how do i print an input but remove one word per line?

Time:10-07

This is the code to do the opposite of what I want to do. This adds a word per line but I want to remove a word per line. Is there a way to reverse this loop?

lst = input("Enter a phrase: ")

word = lst.split()

for i in range(len(word)):
    print(' '.join(word[:i]))
print(lst)

CodePudding user response:

You can change your range to loop backwards:

lst = input("Enter a phrase: ")

word = lst.split()

for i in range(len(word), 0, -1):
    print(' '.join(word[:i]))
print(lst)

Displays:

Enter a phrase: I like pizza
I like pizza
I like
I
I like pizza

CodePudding user response:

Try this, hope it helps:

lst = input("Enter a phrase: ")

words = lst.split()

while words:
    print(' '.join(words))
    words.pop(-1)

CodePudding user response:

You can do this with a little change to the slice index

print(' '.join(word[:len(word)-i]))
  • Related