python 与字符串的映射
我使用 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
就像我想要的那样。
除了可能有一种我还没有见过的使用内置函数的方法之外,为什么第一种方法会失败,而第二种方法会做我需要的事情呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
replacer
的参数顺序是两者之间的区别。如果您更改第一个版本中的参数顺序,它的行为将与第二个版本类似。The ordering of the arguments to
replacer
is what makes the difference between the two. If you changed the argument ordering in the first version it'd behave like the second version.不要使用内置名称(例如
str
)作为您自己的标识符,这只是自找麻烦并且没有任何好处。除此之外,您的第一个版本在
str
(第二个 参数)上循环 - 列表['e', 'l', 'o']< /code> - 所以当然它将返回一个恰好包含三个项目的字符串 - 你怎么能期望它返回任何其他长度的字符串?!使用
str
来命名 list 参数尤其是不正当且容易出错的。第二个版本在
str
上循环,即 first 参数 - 字符串'hello world'
所以它当然返回一个字符串 那个长度。Don't use built-in names such as
str
for your own identifiers, that's just asking for trouble and has no benefit whatsoever.Apart from that, your first version is looping on
str
, the second argument -- the list['e', 'l', 'o']
-- so of course it will return a string of exactly three items -- how could you expect it to return a string of any other length?! Usingstr
to name a list argument is particularly perverse and bug-prone.The second version loops on
str
, the first argument -- the string'hello world'
so of course it's returning a string of that length.你在第一个中向后传递它。应该是应该是
You're passing it in backwards in the first one. It should be should be