Home > OS >  how to replace string between to character in python?
how to replace string between to character in python?

Time:11-10

i have a string like _%#DDMM#%_ or _%#NAME#%_. how can i delete strings between _%# and #%_ in text?

CodePudding user response:

Assuming you want to delete the whole thing, you could use:

import re
re.sub('_%#.*?#%_', '', text)

Example:

text = '123 _%#abcd#%_ def'
import re
re.sub('_%#.*?#%_', '', text)

Output: 123 def

If you want to remove only the inner part:

text = '123 _%#abcd#%_ def'
import re
re.sub('(?<=_%#).*?(?=#%_)', '', text)

Output: '123 _%##%_ def'

  • Related