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

Replace specific expression in python

I want to replace a string contains "${}" with "*" in python.
example, replace:

"This is ${ali} from team"

with

"This is * from team"

I’ve tried this but does not work:

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

re.sub("^$.*}$", "*",str)

>Solution :

import re
s = "This is ${ali} from team ${asda} "

s = re.sub(r'\${.[^}]+}','*',s)
print(s)

OUTPUT

This is * from team *

Pythonic way

s = "This is ${ali} from team ${asd}"

s = list(s)
try:
    while '$' in s and '}' in s:
        s[s.index('$'):s.index('}')+1] = '*'
except ValueError:
    pass
s = ''.join(s)
print(s) # → This is * from team *

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