如何将行号添加到多行字符串

How to add line numbers to multiline string

我有一个如下所示的多行字符串:

txt = """
some text

on several

lines
"""

如何打印此文本,使每一行都以行号开头?

这可以通过组合 split("\n")join(\n)enumerate 和列表理解来完成:

def insert_line_numbers(txt):
    return "\n".join([f"{n+1:03d} {line}" for n, line in enumerate(txt.split("\n"))])

print(insert_line_numbers(txt))

它产生输出:

001 
002 some text
003 
004 on several
005 
006 lines
007 

我是这样做的。只需将文本分成几行。添加行号。使用 format 打印 int 行号和 string. 的 2 个占位符和 .

之后的 space
count = 1
txt = '''Text
on
several
lines'''
txt = txt.splitlines()
for t in txt:
    print("{}{}{}{}".format(count,"."," ",t))
    count += 1

输出

1. Text
2. on
3. several
4. lines

我通常使用带有函数属性的正则表达式替换:

def repl(m):
    repl.cnt+=1
    return f'{repl.cnt:03d}: '

repl.cnt=0          
print(re.sub(r'(?m)^', repl, txt))

打印:

001: 
002: some text
003: 
004: on several
005: 
006: lines
007: 

这使您可以轻松地仅对包含文本的行进行编号:

def repl(m):
    if m.group(0).strip():
        repl.cnt+=1
        return f'{repl.cnt:03d}: {m.group(0)}'
    else:
        return '(blank)'    

repl.cnt=0  
print(re.sub(r'(?m)^.*$', repl, txt))

打印:

(blank)
001:    some text
(blank)
002:    on several
(blank)
003:    lines
(blank)
for n, i in enumerate(txt.rstrip().split('\n')):
    print(n, i)
0 
1 some text
2 
3 on several
4 
5 lines