1

I have taken the input from the user and then converted the string into the list object using the split method. Then reversed the list using reverse function and it is working well. But the problem is that I'm unable to get the last word from the string.

I'm have checked my loop and it's working fine.

s=input('enter any string:')
l=s.split()
l1=reversed(l)
for i in l1:
    l2=' '.join(l1)
    print(l2)

input:

learning python is very easy

output:

very is python learning

4 Answers 4

2

reversed is a generator function that returns an iterator, so when you use a for statement to iterate over it, it consumes the first item (the last word in your case) for the first iteration, during which you consume the rest of the iterator with the ' '.join method, which is why it returns only all but the last word in the string for the next print statement to output.

In other words, you don't need the for loop. The ' '.join method alone will iterate through the iterator for you:

s=input('enter any string:')
l=s.split()
l1=reversed(l)
l2=' '.join(l1)
print(l2)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the reverse method to reverse l in place.

l = s.split(" ").reverse()
return l[0]  #this would return the first word of reversed arr or last word of string

Comments

1
s=" ".join(input('enter any string:').split(' ')[::-1])
print(s)

This is a simple solution to your expected output.

Comments

0

One-liner for reversing the given string.

>>> a=input()
python is very easy
>>> s=' '.join(a.split()[::-1])
>>> s
'easy very is python'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.