Python 라이브러리 - textwrap

textwrap

공식 문서 링크

source code

shorten

문자열을 원하는 길이에 맞게 줄여 표시

import textwrap

# shorten
text = "life is too short, you need python"

result = textwrap.shorten(text=text, width=15)
print(result)   # life is [...]

문자열에 포함된 모든 연속 공백은 하나의 공백 문자로 줄어든다. 축약된 문자열임을 뜻하는 [...] 역시 전체 길이에 포함되며 문자열은 단어 단위로 길이에 맞게 줄어든다.

한글도 마찬가지로 적용된다. 단, 한글 1 문자를 길이 2가 아닌 1로 계산한다.

text = "인생은 짧으니 파이썬이 필요해"

result = textwrap.shorten(text=text, width=15)
print(result)   # 인생은 짧으니 [...]

축약 표시 [...]를 다른 문자로 변경하고 싶으면 매개변수 placeholder를 이용한다.

result = textwrap.shorten(text=text, width=15, placeholder='...')
print(result)   # 인생은 짧으니 파이썬이...

wrap

긴 문자열을 원하는 길이로 줄 바꿈(wrapping)할 때 사용하는 함수

long_text = "life is too short, you need python. " * 10

result = textwrap.wrap(text=long_text, width=50)
print(result)   
# ['life is too short, you need python. life is too', 'short, you need python. life is too short, you', 'need python. life is too short, you need python.', 'life is too short, you need python. life is too', 'short, you need python. life is too short, you', 'need python. life is too short, you need python.', 'life is too short, you need python. life is too', 'short, you need python.']

wrap() 함수는 문자열을 width 길이만큼 자르고 이를 리스트로 반환합니다.

print('\n'.join(result))
"""
life is too short, you need python. life is too
short, you need python. life is too short, you
need python. life is too short, you need python.
life is too short, you need python. life is too
short, you need python. life is too short, you
need python. life is too short, you need python.
life is too short, you need python. life is too
short, you need python.
"""

이처럼 join() 함수로 문자열 사이에 줄 바꿈 문자(\n)를 넣어 하나로 합친 다음 출력할 수 있습니다.

fill()

fill()메서드를 사용하면 위의 과정을 한 번으로 줄일 수 있습니다.

result = textwrap.fill(text=long_text, width=70)
print(result)
"""
life is too short, you need python. life is too
short, you need python. life is too short, you
need python. life is too short, you need python.
life is too short, you need python. life is too
short, you need python. life is too short, you
need python. life is too short, you need python.
life is too short, you need python. life is too
short, you need python.
"""

 

 


 

http://www.yes24.com/Product/Goods/109209932

 

Do it! 점프 투 파이썬 라이브러리 예제 편 - YES24

『Do it! 점프 투 파이썬』의 후속 편 출간!다양한 예제로 배우는 파이썬 라이브러리 실전 안내서!이 책은 『Do it! 점프 투 파이썬』의 박응용 저자가 그동안 수많은 독자에게 받았던 ‘이제 무엇

www.yes24.com

Do it! 점프 투 파이썬 라이브러리 예제 편⌟ 책을 공부하며 요약・정리한 내용입니다.


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

Python 라이브러리 - datetime  (0) 2023.05.11
Python 라이브러리 - re  (0) 2023.05.11
Python에서의 캡슐화  (0) 2023.04.28
Subtype in Python  (0) 2023.03.30
First Class Function  (0) 2023.03.30