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?
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?
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
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)
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
for n, i in enumerate(txt.rstrip().split('\n')):
print(n, i)
0
1 some text
2
3 on several
4
5 lines