Search code examples
pythonregexregexp-replace

Attach string for matching substring


I have the following string

test = "if row['adm.w'] is 'Bad' and row['rem'] not empty"

I want to add str(...) for those tokens which are row[...], how can I do this in regex? I came up with this and it's not working as intended:

re.sub(r"'([^row[']*)'", r"str(['\1'])", test)

I want the end result to be

test = "if str(row['adm.w']) is 'Bad' and str(row['rem']) not empty"

Solution

  • This should work:

    >>> re.sub(r"(row\[.*?\])", r"str(\1)", test)
    "if str(row['adm.w']) is 'Bad' and str(row['rem']) not empty"