0

I noticed the following strange behaviour when I try to use replace in a function. Let's say we have the following function:

def string_replace(string, arg):
    string.replace(arg, "")
    return string

This function is supposed to get rid of the arg in the string argument, but it doesn't seem to work. For example:

string_replace('There.', '.') < There.

But if I type: "There.".replace(".", "") everything goes smoothly.

Any logical explanation?

thanasissdr
  • 807
  • 1
  • 10
  • 26

1 Answers1

2

In Python strings are immutable so you are not modifying it in place. Any of the following will work:

def string_replace(string, arg):
    string = string.replace(arg, "")
    return string

def string_replace(string, arg):
    return string.replace(arg, "")
Jim Wright
  • 5,905
  • 1
  • 15
  • 34