Practice makes perfect reverse


I'm trying to reverse a string and it is working but is only returning reversed indexes (6543210) instead of the reversed string (which should be "!nohtyP") I don't know how to convert the numbers back into the letters to which they are assigned. Help is appreciated!

I get the error message: Oops, try again. Your function fails on reverse("Python!"). It returns "6543210" when it should return "!nohtyP".

Replace this line with your code. 
def reverse(text):
    reverse = ""
    for text in range(len(text)-1, -1, -1):
        reverse = reverse + str(text)
    return reverse


I wouldn't recommend you using text as an index(items) in your for loop. It just looks confusing and some IDEs may not take it well (another reason will come up soon).
Try using a different variable name eg.

for letters in range(len(text)-1, -1, -1):

Next, Python considers the your text in the for loop for text in...: to be your indexes in order to iterate. So they are numbers.
Therefore, when you do str(text), you are basically turning your index numbers into strings: "543210". You can do text[index] instead, where [index] is the variable name you used in your loop and text is the string you inputted. Since you used text, text[text] may be confusing hence another reason why you use a different name for your index.


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