-1

I am working on a function to reverse a string and when I run it I get two errors, one at tot -= i showing TypeError: unsupported operand type(s) for -=: 'str' and 'str', and at print(reverse(thestr)).

However, if I put the + in tot += i, it works. How can I solve this, as for my understanding when using - it will go in reverse?

def reverse(c):
    tot = ''
    for i in c:
        tot -= i
    return tot
thestr = 'This is a Test'
print(reverse(thestr))
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
GiddyHeaD
  • 49
  • 6

2 Answers2

1

for my understanding the use the - it will go in reverse

That's incorrect.

To prepend, you can do this:

tot = i + tot

Or, to solve the problem more pythonically, use reversed():

def reverse(c):
    tot = ''
    for i in reversed(c):
        tot += i
    return tot

Which can then be simplified with ''.join():

def reverse(c):
    return ''.join(reversed(c))

Or simply use a reverse slice:

def reverse(c):
    return c[::-1]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

your code doesn't reverse a string. this will:

def reverse(c):
    l = len(c)
    tot = ''
    for i in range(l):
        tot += c[l - i - 1]
    return tot
thestr ='This is a Test'
print(reverse(thestr))
0xedb
  • 354
  • 2
  • 8
  • 1
    It's a bit simpler to do `for i in reversed(range(len(c))): tot += c[i]`, but there's no point using indices when you could just do `for i in reversed(c): tot += i` like I wrote in [my answer](https://stackoverflow.com/a/65030871/4518341). – wjandrea Nov 27 '20 at 01:06
  • using indices is a better place to start IMO. a beginner may be confused how `reversed` works – 0xedb Nov 27 '20 at 01:17