cv izrada cv izrada - 1 year ago 31
Python Question

str.replace won't work within a function

Why is this not working?

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


output:

abcdč

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download