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č
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č
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)
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č