Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add string to a string based on condition

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 : '='"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading