行番号追加
カスタマイズ可能な区切り文字、開始番号、ステップ、ゼロパディングで任意のテキストに行番号を追加します。
よくある質問
コード実装
def add_line_numbers(text, start=1, step=1, sep=". ", pad=False, skip_empty=False):
lines = text.split("\n")
total = sum(1 for l in lines if (not skip_empty or l.strip())) if skip_empty else len(lines)
max_num = start + (total - 1) * step
width = len(str(max_num))
num = start
result = []
for line in lines:
if skip_empty and not line.strip():
result.append(line)
continue
num_str = str(num).zfill(width) if pad else str(num)
result.append(f"{num_str}{sep}{line}")
num += step
return "\n".join(result)
text = """Hello world
This is line two
Fourth line here"""
print(add_line_numbers(text, start=1, step=1, sep=". ", pad=True))Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.