I implemented a version of the str_replace function available in php using python. Here is my original code that didn’t work
def replacer(items,str,repl):
return "".join(map(lambda x:repl if x in items else x,str))
test = "hello world"
print test
test = replacer(test,['e','l','o'],'?')
print test
but this prints out
hello world
???
the code i got to do as expected is
def replacer(str,items,repl):
x = "".join(map(lambda x:repl if x in items else x,str))
return x
test = "hello world"
print test
test = replacer(test,['e','l','o'],'?')
print test
which prints out
hello world
h???? w?r?d
just like I wanted it to.
Aside from the fact that there is probably a way using builtins that i haven’t seen yet, why does the first way fail and the second way do what I need it to?
The ordering of the arguments to
replaceris what makes the difference between the two. If you changed the argument ordering in the first version it’d behave like the second version.