Dev/Python

[Python] textwrap.dedent

dragonhyeon 2025. 9. 18. 21:27
728x90
반응형

멀티라인 문자열 (Multiline Strings)

  • """ ... """ 멀티라인 문자열을 그대로 쓰면, 들여쓰기가 코드 전체 스타일과 어긋나서 보기가 안 예쁠 수 있음
def main():
    prompt = f"""When I use multi-line strings in Python,
the indentation style looks misaligned and messy.
How can I fix this?
"""
    print(prompt)
  • 아래와 같이 코드 작성시 출력 앞부분에 공백이 들어감
def main():
    prompt = f"""
    When I use multi-line strings in Python,
    the indentation style looks misaligned and messy.
    How can I fix this?
    """
    print(prompt)

    When I use multi-line strings in Python,
    the indentation style looks misaligned and messy.
    How can I fix this?

textwrap.dedent

def main():
    prompt = textwrap.dedent(text=f"""
        You can use textwrap.dedent to clean up the indentation of multi-line strings.
        This way, you can keep your code indented nicely without affecting the actual string content.
    """).strip()
    print(prompt)
  • dedent: 여러 줄로 된 문자열의 모든 줄 앞 부분 공백 제거 함수
  • strip: 문자열의 앞뒤에 있는 특정 문자를 제거하는 함수. 아무값도 주지 않으면 공백 및 개행 제거. 특정 문자 지정도 가능. prompt engineering 에서는 strip 도 함께 쓰는것이 좋은 practice.
728x90
반응형

'Dev > Python' 카테고리의 다른 글

Python f-string  (2) 2025.08.23
Python dotenv 사용법 및 원리  (3) 2025.08.17