파이썬 textwrap 모듈을 빠르게 사용하기 위한 치트시트입니다. wrap, fill, dedent, indent, shorten 함수로 텍스트 포맷팅하는 패턴을 최소 예제로 정리합니다.
textwrap 모듈은 텍스트 줄바꿈과 들여쓰기를 다루는 도구입니다. CLI 출력, 이메일 본문, 리포트 생성 등에서 텍스트를 깔끔하게 정렬할 때 유용합니다.
언제 이 치트시트를 보나?
긴 텍스트를 특정 너비로 줄바꿈해야 할 때
멀티라인 문자열의 들여쓰기를 제거하고 싶을 때
텍스트를 일정 길이로 자르고 말줄임표를 붙일 때
핵심 함수
1
2
3
4
5
6
7
importtextwraptextwrap.wrap(text,width=70)# 리스트로 분할textwrap.fill(text,width=70)# 문자열로 줄바꿈textwrap.dedent(text)# 공통 들여쓰기 제거textwrap.indent(text,prefix)# 들여쓰기 추가textwrap.shorten(text,width)# 길이 제한 + 말줄임
최소 예제
1. wrap - 리스트로 분할
1
2
3
4
5
6
7
8
9
10
11
12
13
14
importtextwraptext="Python is a programming language that lets you work quickly and integrate systems more effectively."lines=textwrap.wrap(text,width=30)print(lines)# ['Python is a programming', 'language that lets you work', 'quickly and integrate systems', 'more effectively.']forlineinlines:print(line)# Python is a programming# language that lets you work# quickly and integrate systems# more effectively.
2. fill - 줄바꿈된 문자열
1
2
3
4
5
6
7
8
9
importtextwraptext="Python is a programming language that lets you work quickly and integrate systems more effectively."formatted=textwrap.fill(text,width=40)print(formatted)# Python is a programming language that# lets you work quickly and integrate# systems more effectively.
3. dedent - 들여쓰기 제거
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
importtextwrap# 함수 내 멀티라인 문자열defget_help():help_text="""\
Usage: program [options]
Options:
-h Show help
-v Verbose mode
"""returntextwrap.dedent(help_text)print(get_help())# Usage: program [options]# # Options:# -h Show help# -v Verbose mode
importtextwraptext="""First line
Second line
Third line"""# 모든 줄에 들여쓰기indented=textwrap.indent(text,' ')print(indented)# First line# Second line# Third line# 조건부 들여쓰기 (비어있지 않은 줄만)text_with_empty="Line 1\n\nLine 2"indented=textwrap.indent(text_with_empty,'> ',predicate=lambdaline:line.strip())print(indented)# > Line 1# # > Line 2
5. shorten - 길이 제한
1
2
3
4
5
6
7
8
9
10
11
12
importtextwraptext="Hello World! This is a very long text that needs to be shortened."short=textwrap.shorten(text,width=30)print(short)# Hello World! This is a [...]# 커스텀 placeholdershort=textwrap.shorten(text,width=30,placeholder="...")print(short)# Hello World! This is a...
6. TextWrapper 클래스 (세부 설정)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
importtextwrapwrapper=textwrap.TextWrapper(width=40,initial_indent='* ',# 첫 줄 들여쓰기subsequent_indent=' ',# 이후 줄 들여쓰기break_long_words=False,# 긴 단어 자르지 않음break_on_hyphens=True# 하이픈에서 줄바꿈)text="This is a demonstration of the TextWrapper class with custom settings."print(wrapper.fill(text))# * This is a demonstration of# the TextWrapper class with# custom settings.
importtextwrapitems=["First item with a long description that might wrap","Second item","Third item with another long description"]wrapper=textwrap.TextWrapper(width=40,initial_indent=' - ',subsequent_indent=' ')foriteminitems:print(wrapper.fill(item))# - First item with a long# description that might wrap# - Second item# - Third item with another long# description
8. dedent + fill 조합
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
importtextwrapdefprint_help():help_text=textwrap.dedent("""\
This is a help message that explains how to use the program.
It can span multiple lines and will be properly formatted
when displayed to the user.
""")print(textwrap.fill(help_text,width=50))print_help()# This is a help message that explains how to# use the program. It can span multiple lines# and will be properly formatted when displayed# to the user.
9. 코드 블록 보존
1
2
3
4
5
6
7
8
9
10
importtextwrap# wrap은 코드를 망가뜨릴 수 있음code="def hello(): print('world')"print(textwrap.fill(code,width=20))# 코드가 이상해짐# 코드는 그대로 두고 설명만 wrapdescription="This function prints a greeting message to the console."formatted_desc=textwrap.fill(description,width=40)print(f"{formatted_desc}\n\n{code}")
TextWrapper 주요 옵션
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
importtextwrapwrapper=textwrap.TextWrapper(width=70,# 최대 줄 너비initial_indent='',# 첫 줄 접두사subsequent_indent='',# 이후 줄 접두사expand_tabs=True,# 탭을 공백으로tabsize=8,# 탭 크기replace_whitespace=True,# 공백 정규화fix_sentence_endings=False,# 문장 끝 공백 2개break_long_words=True,# 긴 단어 자르기break_on_hyphens=True,# 하이픈에서 줄바꿈drop_whitespace=True,# 줄 시작/끝 공백 제거max_lines=None,# 최대 줄 수placeholder=' [...]'# 생략 시 표시)
자주 하는 실수
1. dedent가 작동하지 않을 때
1
2
3
4
5
6
7
8
9
10
11
12
13
14
importtextwrap# 첫 줄에 텍스트가 있으면 dedent 작동 안 함bad=""" Line 1
Line 2"""print(textwrap.dedent(bad))# 변화 없음# 첫 줄을 비우거나 \ 사용good="""\
Line 1
Line 2"""print(textwrap.dedent(good))# Line 1# Line 2