python 映射与字符串

标签 python string dictionary lambda

我使用 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/

相关文章:

c - 使用替换密码的加密不会生成有效的 ASCII 输出

python - 组合功能

algorithm - 分词算法

python - 如果我想使用 CGI session ,我应该在 Python 中考虑哪些模块?

python - 如何将多个网格节点附加到 blender 中的一个对象?

python - 问题,在 python 3.7 中构建开关盒

java - 格式化字符串以匹配模式

写入文件的 Python 函数不会在下次调用时切换到 else 语句

ruby - 在Ruby中从字符串中删除元音

Python如何在一行中打印字典?