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)
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.
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.
The replace method takes three arguments — two are required, the third is optional.
By default, the count is set to zero, which means the re. sub() method will replace all pattern occurrences in the target string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With