'Why does this reverse the string?
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?
Solution 1:[1]
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
Solution 2:[2]
Its because you prepend the characters in order. On each iteration, the i'th character becomes the first character of the result, shifting those already added to the right. 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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
