python/모듈

[Python] textwrap

wjwkddyd221001 2023. 1. 30. 21:51

1. 문자열 줄여 표시하기

textwrap.shorten(sentence, width = 15, placeholder = "...")

import textwrap
sentense = "Life is too short, you need python"
result = textwrap.shorten(sentense, width=15)
print(result) # Life is [...]

result = textwrap.shorten(sentense, width=15, placeholder="...")
print(result) # Life is too...

 

2. 긴 문장 줄 바꿈하기

textwrap.wrap(sentense, width = 70)

긴 문자열을 width 길이만큼 자르고 리스트로 만들어 반환

import textwrap

# textwrap.wrap() 함수는 긴 문자열을 width 길이만큼 자르고 이를 리스트로 만들어 반환한다.
long_text = 'Life is too short, you need python. ' * 10
result = textwrap.wrap(long_text, width=70)
print('\n'.join(result))