【发布时间】:2020-06-23 22:22:35
【问题描述】:
我想替换 mystring 中任何数字前面的 \n,同时保持数字与以前相同。 我尝试了以下方法。
mystring = "\n this \n 1. is \n 2. some \n 3. text \n"
k = re.sub('\n \d', '\d', mystring)
k
我不想替换所有的“\n”。只有前面的数字。但是在我的输出中,数字被替换为“\d”,我想知道如何保持它们相同。
我的输出:
'\n this \\d. is \\d. some \\d. text \n'
预期输出
'\n this 1. is 2. some 3. text \n'
【问题讨论】:
-
您的意思是
\n (\d)并替换为\1? regex101.com/r/IQ40o4/1 -
你不能只删除所有换行符,然后在字符串的每一端添加一个吗?
标签: python regex python-3.x replace