.replace not working?

Screen Link:

My Code:

test = '100,000+'
print(test.replace('+', ''))

for app in google_data:
    n_installs = app[5]
    n_installs.replace('+', '')
    print(n_installs)

What I expected to happen:
100,000
10,000
500,000
5,000,000
50,000,000
etc…

What actually happened:

100,000
10,000+
500,000+
5,000,000+
50,000,000+
n_installs.replace('+', '')

You need to store the output of the above back into n_installs. The replacement doesn’t happen in-place. You need to store it into the variable as well. Otherwise, the value stored in n_installs won’t really get updated.

So, something like -

for app in google_data:
    n_installs = app[5]
    n_installs = n_installs.replace('+', '')
    print(n_installs)
2 Likes

Hello @rolychuter, welcome to the community.

The problem is that you are not assigning the replaced text to anything. In your test, it works because it is inside the print function and so you are telling Python to print the replaced test.

Inside the for, however, as you did not assign the result of the replacement to anything, the variable n_installs is never changed.

There are two solutions to this. you can:

  • Assign the result back to the variable:
n_installs = n_installs.replace('+', '')
  • Replace the string inside the print. This won’t store the replaced string anywhere, though.
print(n_installs.replace('+', ''))
2 Likes

Can’t believe I din’t spot that!! Thanks

1 Like

Always fell for this too :joy::joy:, until I realized that the trick was to think if the data type is mutable or not :grinning:

strings are immutable, meaning the string itself can’t be modified (unlike the variable name holding it).

hope this helps :blush: