Reverse: is text[-] allowed?


#1

https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096#

Below is my code and it works. But does text[-letter] work the same as [::-1] and therefore I should try a different method?

def reverse(text):
    reverse_word = ""
    for letter in range(1, len(text)+1):
        reverse_word += text[-letter]
    return reverse_word

#2

Both examples,

are of the same thing, slicing.

>>> "reverse"[-1]
'e'
>>> "reverse"[-2]
's'
>>> "reverse"[-3]
'r'
>>> "reverse"[-4]
'e'
>>> "reverse"[-5]
'v'
>>> "reverse"[-6]
'e'
>>> "reverse"[-7]
'r'
>>>

More reading: http://pythoncentral.io/cutting-and-slicing-strings-in-python/


#3

your method is fine? the use of -letter is allowed, you still have to code a loop correctly. with [::-1] you have to do nothing at all, then you just get:

def reverse(text):
   return text[::-1]

done.

Your solution is a really elegant one. You should be happy with it :slight_smile:


#4

A post was split to a new topic: Reverse


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.