Home > Net >  Passed argument memory context
Passed argument memory context

Time:04-02

I came across this while coding:

def interpret(command): 
    # comment1: command.replace("()","o").replace("(al)","al") 
    # comment2: print(command)

    res = command.replace("()","o").replace("(al)","al")
    print(res)

interpret("G()(al)")

In the above code, I was expecting the string to be replaced at 'comment1' but, I got the same value passed as an argument i.e. "G()(al)" but on storing it in a different location (here, 'res') I was able to get the expected result.

Could you please point out what made Python remember the 'command' original value or is there something like JavaScript's closure or I am unable to see the simple point here?

CodePudding user response:

According to the official documentation:

str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

Meaning that a new string is created for the data to be stored in. And since you did not store the result of the replacement operations back into the command parameter, the result is never used. Storing the data in another variable res also works and might provide more bug-resistance if you want to perform multiple operations on command that you might re-arrange later on.

  • Related