假设我有以下字符串
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次?
答案 0 :(得分:3)
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)