我使用 python 实现了 php 中可用的 str_replace 函数版本。这是我的原始代码,但不起作用
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
但是这会打印出来
hello world
???
我要做的代码是
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
打印出来
hello world
h???? w?r?d
就像我想要的那样。
除了可能有一种我还没有见过的使用内置函数的方法之外,为什么第一种方法失败而第二种方法做我需要的事情?
最佳答案
replacer
的参数顺序是两者之间的区别。如果您更改了第一个版本中的参数顺序,它的行为将与第二个版本相同。
关于python 映射与字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2260148/