줄 번호 추가
사용자 지정 가능한 구분자, 시작 번호, 스텝, 0 패딩으로 모든 텍스트에 줄 번호를 추가합니다.
자주 묻는 질문
코드 구현
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.