Eric R.
Eric R.

Reputation: 5

Reversing string in a for-loop

I have the following function:

s = 'hello'
rev = ''

for char in s:
    rev = char + rev
return rev

Why does the for loop above add the characters in reverse? I tried using rev += char and it returned the string in the original order, s. This was mentioned in a video and they didn't explain properly, just said "Python's for loop over string doesn't work that way". I want to know why it does this, so in the future I will be more inclined to avoid these mistakes.

Another question is, can I implement this type of line in the for-loop over lists and will it output the reverse of the list? Since lists are mutable.

Upvotes: 0

Views: 291

Answers (2)

Austo
Austo

Reputation: 26

In the loop you have, your for loop is defined as:

s = 'happy'
rev = ''

for char in s:
    rev = ch + rev

If we look at this going through the first few iterations, we would get: h ah pah ppah yppah

This is because as you update the variable rev, you are adding the next character (char) in front of rev through your definition.

rev = NEW CHARACTER + CURRENT REV so looking at the final iteration, where we add y, you're adding:

rev = NEW CHARACTER (Y) + CURRENT REV (PPAH), basically stating you are adding PPAH to the letter y, instead of adding y to PPAH.

The loop can be easily fixed by swapping ch and rev, making it:

for char in s:
    rev = rev + char

Upvotes: 1

ascripter
ascripter

Reputation: 6223

The +-operator on strings means concatenation which is not commutative. So there's a difference between char + rev and rev + char.

Successively prepending the next character in front effectively reverses the string.

Upvotes: 3

Related Questions