Home > database >  Why does this reverse the string?
Why does this reverse the string?

Time:03-16

def reverse(s):
  str = ""
  for i in s:
    str = i   str
  return str

I don't understand how using str in this case reverses the string?

CodePudding user response:

That's terrible naming btw. (And it's replacing the reserved keyword str).

I believe this should make it more readable. Explanations are given in the comments.

def reverse(string):
    reversed_string = ""
    for letter in string:
        reversed_string = letter   reversed_string
    
    return reversed_string

CodePudding user response:

Its because you prepend the characters in order. On each iteration, the i'th character becomes the first character of the result. In python we often use print to see what is going on. A quick change to the script shows the steps

def reverse(s):
    str = ""
    for i in s:
        print(repr(i), " ", repr(str), end="")
        str = i   str
        print(" ==>", repr(str))
    return str

print(reverse("abcd"))

Result

'a'   '' ==> 'a'
'b'   'a' ==> 'ba'
'c'   'ba' ==> 'cba'
'd'   'cba' ==> 'dcba'
dcba
  • Related