1

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?

Georgy
  • 12,464
  • 7
  • 65
  • 73
cknoll
  • 2,130
  • 4
  • 18
  • 34

4 Answers4

2

This can be done with a combination of split("\n"), join(\n), enumerate and a list comprehension:

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

It produces the output:

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

cknoll
  • 2,130
  • 4
  • 18
  • 34
  • Does it have to be `001` doesn't look right. Should it be just `1` – Abhishek Rai Oct 31 '20 at 11:23
  • This is IMHO just a matter of taste. If leading zeros are unwanted just use `f"{n+1} {line}"` instead of `f"{n+1:03d} {line}`. I thought it might be useful to ensure constant indentation for the first 999 lines. – cknoll Oct 31 '20 at 11:33
  • I think if to use numbers without leading zeros then at least they should be leading-padded with spaces instead of zeros. But I like zeros solution more. – Arty Oct 31 '20 at 11:42
  • Just a small question. Why would you want line numbers without any lines? – Abhishek Rai Oct 31 '20 at 11:58
2

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)
dawg
  • 98,345
  • 23
  • 131
  • 206
1

I did it like this. Simply break the text into lines. Add a line number. Use format to print int line number and the string. 2 place holders for . and a space after the .

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

Output

1. Text
2. on
3. several
4. lines
Abhishek Rai
  • 2,159
  • 3
  • 18
  • 38
  • Valid solution, which can easily be understood. However, to make it copy-paste-ready (and be a good example for newcommers) it should comply with PEP-8 coding style (argument spacing). (And: manually increasing counting variables is IMHO considered "unpythonic". Thus I used `enumerare(...)`) – cknoll Oct 31 '20 at 11:42
  • Oh I see. Well, I am not that advanced. Happy coding. – Abhishek Rai Oct 31 '20 at 11:46
1
for n, i in enumerate(txt.rstrip().split('\n')):
    print(n, i)
0 
1 some text
2 
3 on several
4 
5 lines
Henry Tjhia
  • 742
  • 1
  • 5
  • 11