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

MSeifert
  • 145,886
  • 38
  • 333
  • 352

2 Answers2

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
Psidom
  • 209,562
  • 33
  • 339
  • 356
0

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

mhmyxz
  • 1
  • 2