Search code examples
pythonpretty-printmultilinestring

How to add line numbers to multiline string


I have a multiline string like the following:

txt = """
some text

on several

lines
"""

How can I print this text such that each line starts with a line number?


Solution

  • I usually use a regex substitution with a function attribute:

    def repl(m):
        repl.cnt+=1
        return f'{repl.cnt:03d}: '
    
    repl.cnt=0          
    print(re.sub(r'(?m)^', repl, txt))
    

    Prints:

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

    Which allows you to easily number only lines that have text:

    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))
    

    Prints:

    (blank)
    001:    some text
    (blank)
    002:    on several
    (blank)
    003:    lines
    (blank)