Home > Mobile >  Replace specific expression in python
Replace specific expression in python

Time:05-08

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:

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

CodePudding user response:

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

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 *

CodePudding user response:

Try F-string methods like example below, '''

  • = something

print(f"Print text with {*} in the middle") '''

CodePudding user response:

You could do that using Regular Expressions.

import re


test_str = "This is ${ali} from team"
sub = "*"

regex = r"\$\{[^;]*\}"
result = re.sub(regex, sub, test_str, 0)

print(result)
// "This is * from team"
  • Related