str.replace won't work within a function

2019-07-14 08:58发布

问题:

Why is this function not returning the result of the replace?

def replacechar(str):
    str.replace("č","c")
    str.replace("a","y")
    return str
p= "abcdč"
replacechar(p)
print(p) 

output:

abcdč

回答1:

str.replace is not an inplace operation. It returns a string. The good news is that your function will work with minimal modification.

def replacechar(string):
    return string.replace("č","c").replace("a","y")

Next, you will need to assign the return value back to p:

p = replacechar(p)

Also, don't use str to name an object because you already have something with that name.


Alternatively, have you considered str.translate?

_TAB = str.maketrans({'č' : 'c', 'a' : 'y'})
def replacechar(string):
    return string.translate(_TAB)


回答2:

replace() returns a copy of the string in which the occurrences of old have been replaced with new.

str.replace has to be assigned back to str in order to return the updated string.

But in your above function you are not overwriting the variable str.

def replacechar(str):
    str = str.replace("č","c")
    str = str.replace("a","y")
    return str
p= "abcdč"
print replacechar(p)
print(p)

Output:

ybcdc
abcdč