Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing two arguments to replace function for Re.sub

Tags:

python

regex

How can I pass two variables to my replace function?

I have defined it as

def replace(line,suppress)

Calling it like 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 exactly 2 arguments (1 given)
like image 510
Apollo Avatar asked Oct 21 '14 20:10

Apollo


People also ask

How do you replace re subs?

If you want to replace a string that matches a regular expression (regex) instead of perfect match, use the sub() of the re module. In re. sub() , specify a regex pattern in the first argument, a new string in the second, and a string to be processed in the third.

How do I replace only part of a match with Python re sub?

Put a capture group around the part that you want to preserve, and then include a reference to that capture group within your replacement text. @Amber: I infer from your answer that unlike str. replace(), we can't use variables a) in raw strings; or b) as an argument to re. sub; or c) both.

How many arguments pass in replace function?

The replace method takes three arguments — two are required, the third is optional.

Does re sub replace all instances?

By default, the count is set to zero, which means the re. sub() method will replace all pattern occurrences in the target string.


1 Answers

As has been mentioned, when re.sub calls your function, it only passes one argument to it. The docs indicate this is a match object (presumably the line variable?)

If you want to pass additional arguments, you should wrap your function up in a lambda expression.

So something like:

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

or

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

Note the use of suppress=suppress in the signature of the second lambda. This is there to ensure the value of suppress used is the value of suppress when the lambda was defined. Without that, the value of suppress used is the value of suppress when the function is executed. In this case, it actually wouldn't matter (as the lambda is used immediately after definition, so suppress will never be changed between definition and execution), but I think it's important you understand how lambda works for using it in the future.

like image 142
three_pineapples Avatar answered Oct 19 '22 23:10

three_pineapples