-1

I want to replace \n in front of any digit in mystring, while keeping the digit the same as before. I tried the following.

mystring = "\n this \n 1. is \n 2. some \n 3. text \n"
k = re.sub('\n \d', '\d', mystring)
k

I do not want to replace all "\n". Only the ones in front digits. However in my output, the digits are replaced with "\d" and I want to know how to keep them the same.

My output:

'\n this \\d. is \\d. some \\d. text \n'

expected output

'\n this 1. is 2. some 3. text \n'
nautograph
  • 254
  • 2
  • 10

1 Answers1

1

You could use a capturing group \n (\d) and in the replacement use r"\1"

To match 1 or more digits use \d+

Regex demo | Python demo

For example

import re
mystring = "\n this \n 1. is \n 2. some \n 3. text \n"
k = re.sub(r"\n (\d)", r"\1", mystring)
print(k)

Output

this 1. is 2. some 3. text

The fourth bird
  • 154,723
  • 16
  • 55
  • 70