-5

I need to replace macro(param) with param

mystring = "function(macro(param)) { a = call(1)};"

and my goal is

"function(param) { a = call(1)};"

the param is variable, it has to work also for

mystring = "function(macro(another_param)) { a = call(1)};"
"function(another_param) { a = call(1)};"

and in the text around could be anything and this text should be not affected.

Meloun
  • 13,601
  • 17
  • 64
  • 93
  • `mystring.replace('macro(param)', 'param')`? – jonrsharpe Nov 03 '15 at 12:26
  • Or `mystring.replace('macro(', '').replace('))', ')')` – MrAlexBailey Nov 03 '15 at 12:27
  • Possible duplicate of [Replacing specific words in a string (Python)](http://stackoverflow.com/questions/12538160/replacing-specific-words-in-a-string-python) – Ahsanul Haque Nov 03 '15 at 12:29
  • sorry for bad describing of the problem, param could be anything and .replace('))', ') is not good enough for me, because it could destroy another )) in my string. – Meloun Nov 03 '15 at 12:31
  • If `param` can be variable then use a variable: `mystring.replace('macro(' + param + ')', param)`. – Matthias Nov 03 '15 at 12:39
  • 1
    @Meloun See the edit on this one, it'll be slightly more efficient without the lambda, I had forgotten about the direct reference earlier. – MrAlexBailey Nov 03 '15 at 17:13

1 Answers1

2

You can also use re.sub:

import re

>>> mystring = "function(macro(param)) { a = call(1)};"
>>> re.sub('macro\((.*?)\)', r'\1', mystring)
function(param) { a = call(1)};

>>> mystring = "function(macro(another_param)) { a = call(1)};"
>>> re.sub('macro\((.*?)\)', r'\1', mystring)
function(another_param) { a = call(1)};

Re searches for macro(param***) and puts param*** into a group when it is found, the sub then replaces that entire match with only param***

MrAlexBailey
  • 5,219
  • 19
  • 30