Friday 15 June 2012

python - Passing two arguments to replace function for Re.sub -



python - Passing two arguments to replace function for Re.sub -

how can pass 2 variables replace function?

i have defined

def replace(line,suppress)

calling so:

line = re.sub(r'''(?x) ([\\]*\$\*)| ([\\]*\$\{[0-9]+\})| ([\\]*\$[0-9]+)| ([\\]*\$\{[a-za-z0-9_]+\-.*\})| ([\\]*\$\{[a-za-z0-9_]+\=.*\})| ([\\]*\$[a-za-z0-9_]+)| ([\\]*\$\{[a-za-z0-9_]+\})| ([\\]*\$[\{]+.*) ''',replace,line,suppress)

receiving error:

return _compile(pattern, flags).sub(repl, string, count) typeerror: replace() takes 2 arguments (1 given)

as has been mentioned, when re.sub calls function, passes 1 argument it. docs indicate match object (presumably line variable?)

if want pass additional arguments, should wrap function in lambda expression.

so like:

re.sub('...', lambda line: replace(line, suppress))

or

re.sub('...', lambda line, suppress=suppress: replace(line, suppress))

note utilize of suppress=suppress in signature of sec lambda. there ensure value of suppress used value of suppress when lambda defined. without that, value of suppress used value of suppress when function executed. in case, wouldn't matter (as lambda used after definition, suppress never changed between definition , execution), think it's of import understand how lambda works using in future.

python regex

No comments:

Post a Comment