Home > Back-end >  python regex how to give space after specific string?
python regex how to give space after specific string?

Time:06-02

my code:

text = '12\nx\n$79.17\n8\nx\n$118.75\n6\nx\n$158.33\n4\nx\n$237.50'

re.sub(r'(\n)', '', text)
>>>12x$79.178x$118.756x$158.334x$237.50 

my expected result will be:

 <br> 12x$79.17 <br> 8x$118.75 <br> 6x$158.33 <br> 4x$237.50 <br>

I want to add <br> tag before every whole number.

update1:

text = short_des.replace('\n',' ')
  >>>'12 x $79.17 8 x $118.75 6 x $158.33 4 x $237.50'

now I want to add <br> before every whole number.

CodePudding user response:

One option could be to use re.sub with a dictionary to map the replacements:

text = '12\nx\n$79.17\n8\nx\n$118.75\n6\nx\n$158.33\n4\nx\n$237.50'

repl = {'\nx\n': 'x', '\n': ' <br> '}

import re
out = re.sub(r'(\nx\n|\n)', lambda m: repl.get(m.group()), text)

Output:

'12x$79.17 <br> 8x$118.75 <br> 6x$158.33 <br> 4x$237.50'

NB. As \n is a substring of \nx\n it must come after in the regex to match second.

  • Related