🛠️ToolsShed

添加行号

使用可自定义的分隔符、起始编号、步长和零填充为任何文本添加行号。

常见问题

代码实现

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.