3

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"
Selcuk
  • 57,004
  • 12
  • 102
  • 110
Fazli
  • 171
  • 8

1 Answers1

3

This should work:

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