[python] textwrap

boychaboy·2023년 7월 29일

textwrap.indent()

  • 문자열의 모든 줄 앞에 prefix를 붙여준다.
  • print나 logging에서 들여쓰기나 목록 표시를 좀 더 쉽게 할 수 있다.
MODEL_INFO = textwrap.indent("ver: 1\nname: model", prefix="- ")
> print(MODEL_INFO)
- ver: 1
- name: model

textwrap.dedent()

  • 문자열의 모든 줄에서 왼쪽 공백을 무시한다.
  • 코드에 긴 문자열을 좀 더 보기 좋게 작성할 수 있다.
  • chatGPT Prompt를 코드 내에서 선언해서 쓸 때 유용.
USER_PROMPT = textwrap.dedent(
	"""
    Some messages to ChatGPT
    - Spaces are ignored
    - Every lines are aligned-Left
    """
)
> print(USER_PROMPT)
Some messages to ChatGPT
- Spaces are ignored
- Every lines are aligned-Left

textwrap.wrap()

  • 문자열을 특정 길이로 자른다.
  • print, logging시에 좀 더 보기 좋게 (너무 길지 않게) 문자열을 출력할 수 있다.
  • width 길이로 자른 줄바꿈 없는 문자열을 list 형태로 반환한다.
MESSAGE = textwrap.wrap("Some long text", width=5)
print(MESSAGE)
['Some', 'long', 'text']
profile
no vim no code

0개의 댓글