Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用str.replace()作为map()中的函数_Python - Fatal编程技术网

Python 如何使用str.replace()作为map()中的函数

Python 如何使用str.replace()作为map()中的函数,python,Python,我有一个从excel工作表返回的行列表。我想对行中的每个项目使用replace函数将'替换为\' 但是,这不起作用: row = map(replace('\'', "\\'"), row) 这只是给出了一个关于replace最多接受3个参数但只有2个参数的错误 在python中是否有使用replace with map的方法 map( lambda s: s.replace(...), row ) 或者使用列表 [s.replace(...) for s in row] 或者,您可以使用

我有一个从excel工作表返回的行列表。我想对行中的每个项目使用replace函数将
'
替换为
\'

但是,这不起作用:

row = map(replace('\'', "\\'"), row)
这只是给出了一个关于replace最多接受3个参数但只有2个参数的错误

在python中是否有使用replace with map的方法

map( lambda s: s.replace(...), row )
或者使用列表

[s.replace(...) for s in row]

或者,您可以使用
re
的replace函数。

这里惯用的Python可能使用列表理解:

row = [ x.replace('\'', "\\'") for x in row ]

要替换的第一个参数是函数;您所做的是尝试函数调用

忘了地图吧。使用

row = [x.replace(something, other) for x in row]

理论上,优化的方法是

map(operator.methodcaller("replace", '\'', '\\\''), ...)
在实践中,列表理解可能更整洁


如果您试图转义字符串,可能有更好的方法(例如)

map(operator.methodcaller("replace", '\'', '\\\''), ...)