【问题标题】:Python - How to replace a character and a digit while keeping the digit the same? [duplicate]Python - 如何在保持数字相同的同时替换字符和数字? [复制]
【发布时间】: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) 并替换为\1regex101.com/r/IQ40o4/1
  • 你不能只删除所有换行符,然后在字符串的每一端添加一个吗?

标签: python regex python-3.x replace


【解决方案1】:

您可以使用捕获组 \n (\d) 并在替换中使用 r"\1"

要匹配 1 个或多个数字,请使用 \d+

Regex demo | Python demo

例如

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)

输出

this 1. is 2. some 3. text

【讨论】:

    猜你喜欢
    • 2011-11-24
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多