Python用字符串映射

2 投票
3 回答
4098 浏览
提问于 2025-04-15 19:15

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

正如我想要的那样。

除了可能还有我没发现的内置方法之外,为什么第一种方法失败了,而第二种方法却能满足我的需求呢?

3 个回答

1

你在第一个例子中传递的顺序是反的。应该是这样:

test = replacer(['e','l','o'], test, '?')
3

不要把像 str 这样的内置名称用作你自己的标识符,这样做只会带来麻烦,而且没有任何好处。

除此之外,你的第一个版本是对 str 进行循环,也就是第二个参数——列表 ['e', 'l', 'o']——所以当然它会返回一个正好包含三个项目的字符串,你怎么能指望它返回其他长度的字符串呢?!用 str 来命名一个列表参数是特别不合适的,容易出错。

第二个版本是对 str 进行循环,也就是第一个参数——字符串 'hello world',所以它返回的字符串长度自然就是那个长度。

4

这里提到的replacer的参数顺序就是让两个版本表现不同的原因。如果你把第一个版本的参数顺序改了,它就会像第二个版本那样工作。

撰写回答