surender pal
surender pal

Reputation: 515

"How to get the revers of string using for loop?

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

Upvotes: 1

Views: 109

Answers (4)

Vashdev Heerani
Vashdev Heerani

Reputation: 679

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

This is a simple solution to your expected output.

Upvotes: 1

Ch3steR
Ch3steR

Reputation: 20669

One-liner for reversing the given string.

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

Upvotes: 0

anushka
anushka

Reputation: 345

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

Upvotes: 1

blhsing
blhsing

Reputation: 106891

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)

Upvotes: 2

Related Questions