blob: c3dbd5977e37d6a8e20aac64025e44e2ea1513fa (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import math
def add_line_numbers(code: str) -> str:
lines = code.splitlines()
if not lines:
return code # empty anyway
# cannot use math.ceil() here bc lg100=2
max_digits = math.floor(math.log10(len(lines))) + 1
for n, l in enumerate(lines, 1):
digits_in_n = math.floor(math.log10(n)) + 1
spaces_before_number = max_digits - digits_in_n
lines[n - 1] = " " * spaces_before_number + str(n) + " " + l
return "\n".join(lines)
|