【问题标题】:Python: re.sub replaces only 16 times [duplicate]Python:re.sub 仅替换 16 次 [重复]
【发布时间】:2018-01-22 15:58:49
【问题描述】:

假设我有以下字符串

s = '\t 1\n\t 2\n\t 3\n\t 4\n\t 5\n\t 6\n\t 7\n\t 8\n\t 9\n\t 10\n\t 11\n\t 12\n\t 13\n\t 14\n\t 15\n\t 16\n\t 17\n\t 18\n\t'

我想以字符串“item”开始每个(缩进)行。所以我写了

s = re.sub('\t', '\t\item ', s, re.DOTALL)

我得到的输出是:

    \item  1
    \item  2
    \item  3
    \item  4
    \item  5
    \item  6
    \item  7
    \item  8
    \item  9
    \item  10
    \item  11
    \item  12
    \item  13
    \item  14
    \item  15
    \item  16
     17
     18

为什么只执行前 16 次操作?

【问题讨论】:

  • 因为 re.DOTALL 的值是 16。你传递的不是标志,而是 count 参数。

标签: python regex string python-3.x


【解决方案1】:
s = re.sub('\t', '\t\item ', s, re.DOTALL)

相当于

s = re.sub('\t', '\t\item ', s, count=re.DOTALL)

re.DOTALL 是 16,因为sub 的签名是

sub(pattern, repl, string, count=0, flags=0)

你想要这个:

s = re.sub('\t', '\t\item ', s, flags=re.DOTALL)

【讨论】:

  • 我明白了,太好了,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多