Home > Software engineering >  Add string to a string based on condition
Add string to a string based on condition

Time:11-15

I have the following string:

string1 = "row['adm.1'] is empty: np.nan, row['adm.2'] is empty: 'Null', row['adm.2'] not empty: 'Null', ELSE : '='"

I want to add str(...) for those preceding before is empty. I want the end result to look like this:

string1 = "str(row['adm.1']) is empty: np.nan, str(row['adm.2']) is empty: 'Null', row['adm.2'] not empty: 'Null', ELSE : '='"

How can I achieve this in python? Thanks.

CodePudding user response:

You can use a regex:

import re
re.sub(r'(\S )(?= is empty)', r'str(\1)', string1)

output: "str(row['adm.1']) is empty: np.nan, str(row['adm.2']) is empty: 'Null', row['adm.2'] not empty: 'Null', ELSE : '='"

  • Related