Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use str.replace() as the function in map()

Tags:

python

I have a list of rows returned from an excel sheet. I want to use the replace function on each item in row to replace ' with \'

however, this does not work:

row = map(replace('\'', "\\'"), row)

this just gives an error about replace taking at most 3 arguments but only having 2.

is there a way to use replace with map in python?

like image 434
Ramy Avatar asked Mar 09 '11 22:03

Ramy


2 Answers

map( lambda s: s.replace(...), row )

or use a list comprehension

[s.replace(...) for s in row]
like image 197
Alexander Gessler Avatar answered Oct 01 '22 03:10

Alexander Gessler


The idiomatic Python here is probably to use a list comprehension:

row = [ x.replace('\'', "\\'") for x in row ]
like image 39
dfan Avatar answered Oct 01 '22 02:10

dfan