0

I don't understand why this code doesn't work:

def reverse(string):
    rev_string = []
    for c in range(len(string)):
        rev_string[c]=string[(len(string))-c]
    str(rev_string)
    return rev_string
print(reverse("google"))

and throws this error message:

IndexError: string index out of range

2
  • you know there is a reversed builtin-function? Commented Dec 29, 2016 at 1:42
  • 1
    You can also do return string[::-1] to reverse a string, if you are just trying to reverse a string without a loop. Commented Dec 29, 2016 at 1:45

2 Answers 2

0

There are three problems in your code.

  1. rev_string is an empty list you can not index it, you can use append instead;

  2. you need to use ''.join instead of str to make a string from a list;

  3. list index is 0 based, so max index is len(string) - 1:


def reverse(string):

    rev_string = []
    for c in range(len(string)):
        rev_string.append(string[len(string)-c-1])
​
    return ''.join(rev_string)

print(reverse("google"))
# elgoog
Sign up to request clarification or add additional context in comments.

Comments

0

when len=6 and c=0. you'll get indexerror, since there is no index6

1 Comment

knowing that the logic behind this code itself won't work

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.