wrap and fill use a character count
textwrap.wrap(text, width=70, **kwargs)
textwrap.fill(text, width=70, **kwargs)wrap() returns a list of lines; fill() returns one string. width counts characters, not screen columns.
| Parameter | Description |
|---|---|
text | A single paragraph. Newlines inside the text are treated as whitespace by default. |
width | Maximum length of each wrapped line, measured with len() after the default whitespace processing. The default is 70. It is not a display-cell budget. |
kwargs | Passed to TextWrapper: initial_indent, subsequent_indent, expand_tabs, tabsize, replace_whitespace, break_long_words, and others documented on the class. |
Returns: wrap() returns a list of strings without trailing newlines. fill() returns a single string with newlines between lines.
import textwrap
text = 'Compare two files and highlight every inserted or deleted line.'
print(textwrap.wrap(text, width=20))
print(textwrap.fill(text, width=20))
wide = '宽度测试宽度测试宽度测试'
lines = textwrap.wrap(wide, width=4)
print(lines)
print([len(line) for line in lines])Expected output
['Compare two files', 'and highlight every', 'inserted or deleted', 'line.']
Compare two files
and highlight every
inserted or deleted
line.
['宽度测试', '宽度测试', '宽度测试']
[4, 4, 4]
Related: str methods, unicodedata east_asian_width