1

I am trying to create a program in python in which the user enters a sentence and the reversed sentenced is printed. The code I have so far is:

sentence = raw_input('Enter the sentence')
length = len(sentence)

for i in sentence[length:0:-1]:
    a = i
    print a,

When the program is run it misses out the last letter so if the word was 'hello' it would print 'olle'. Can anyone see my mistake?

T. Green
  • 323
  • 10
  • 20

5 Answers5

3

You need to remove the 0 from your indices range, but instead you can use :

sentence[length::-1]

Also not that then you don't need to loop over your string and use extra assignments and even the length you can simply print the reversed string.

So the following code will do the job for you :

print sentence[::-1]

Demo :

>>> s="hello"
>>> print s[::-1]
'olleh'
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • For completeness: The correct value to put in the middle is `-1` not `0`. The reason is that the end index is exclusive so the indices represented by `length:0:-1` are `length, length-1, ..., 1`. – Bakuriu Sep 30 '15 at 18:09
1

Try This: NO LOOPS using MAP Function

mySentence = "Mary had a little lamb"

def reverseSentence(text):
     # split the text
     listOfWords = text.split()

     #reverese words order inside sentence
     listOfWords.reverse()

     #reverse each word inside the list using map function(Better than doing loops...)
     listOfWords = list(map(lambda x: x[::-1], listOfWords))

     #return
     return listOfWords

print(reverseSentence(mySentence))
Eran Peled
  • 767
  • 6
  • 6
0

The second argument of the slice notation means "up to, but not including", so sentence[length:0:-1] will loop up to 0, but not at 0.

The fix is to explicitly change the 0 to -1, or leave it out (preferred).

for i in sentence[::-1]:
jh314
  • 27,144
  • 16
  • 62
  • 82
0
print ''.join(reversed(raw_input('Enter the sentence')))
Cody Bouche
  • 945
  • 5
  • 10
0

Here you go:

sentence = raw_input('Enter the sentence')
length = len(sentence)

sentence  = sentence[::-1]
print(sentence)

Enjoy!

Some explanation, the important line sentence = sentence[::-1] is a use of Python's slice notation. In detail here.

This leverage of the syntax reverses the indexes of the items in the iterable string. the result is the reversed sentence you are looking for.

Community
  • 1
  • 1
Alea Kootz
  • 913
  • 4
  • 11