Debian Codegraph @

Doc/library/textwrap.rst

raw
1 :mod:`!textwrap` --- Text wrapping and filling
2 ==============================================
3
4 .. module:: textwrap
5 :synopsis: Text wrapping and filling
6
7 .. moduleauthor:: Greg Ward <[email protected]>
8 .. sectionauthor:: Greg Ward <[email protected]>
9
10 **Source code:** :source:`Lib/textwrap.py`
11
12 --------------
13
14 The :mod:`!textwrap` module provides some convenience functions,
15 as well as :class:`TextWrapper`, the class that does all the work.
16 If you're just wrapping or filling one or two text strings, the convenience
17 functions should be good enough; otherwise, you should use an instance of
18 :class:`TextWrapper` for efficiency.
19
20 .. function:: wrap(text, width=70, *, initial_indent="", \
21 subsequent_indent="", expand_tabs=True, \
22 replace_whitespace=True, fix_sentence_endings=False, \
23 break_long_words=True, drop_whitespace=True, \
24 break_on_hyphens=True, tabsize=8, max_lines=None, \
25 placeholder=' [...]')
26
27 Wraps the single paragraph in *text* (a string) so every line is at most
28 *width* characters long. Returns a list of output lines, without final
29 newlines.
30
31 Optional keyword arguments correspond to the instance attributes of
32 :class:`TextWrapper`, documented below.
33
34 See the :meth:`TextWrapper.wrap` method for additional details on how
35 :func:`wrap` behaves.
36
37
38 .. function:: fill(text, width=70, *, initial_indent="", \
39 subsequent_indent="", expand_tabs=True, \
40 replace_whitespace=True, fix_sentence_endings=False, \
41 break_long_words=True, drop_whitespace=True, \
42 break_on_hyphens=True, tabsize=8, \
43 max_lines=None, placeholder=' [...]')
44
45 Wraps the single paragraph in *text*, and returns a single string containing the
46 wrapped paragraph. :func:`fill` is shorthand for ::
47
48 "\n".join(wrap(text, ...))
49
50 In particular, :func:`fill` accepts exactly the same keyword arguments as
51 :func:`wrap`.
52
53
54 .. function:: shorten(text, width, *, fix_sentence_endings=False, \
55 break_long_words=True, break_on_hyphens=True, \
56 placeholder=' [...]')
57
58 Collapse and truncate the given *text* to fit in the given *width*.
59
60 First the whitespace in *text* is collapsed (all whitespace is replaced by
61 single spaces). If the result fits in the *width*, it is returned.
62 Otherwise, enough words are dropped from the end so that the remaining words
63 plus the *placeholder* fit within *width*::
64
65 >>> textwrap.shorten("Hello world!", width=12)
66 'Hello world!'
67 >>> textwrap.shorten("Hello world!", width=11)
68 'Hello [...]'
69 >>> textwrap.shorten("Hello world", width=10, placeholder="...")
70 'Hello...'
71
72 Optional keyword arguments correspond to the instance attributes of
73 :class:`TextWrapper`, documented below. Note that the whitespace is
74 collapsed before the text is passed to the :class:`TextWrapper` :meth:`fill`
75 function, so changing the value of :attr:`.tabsize`, :attr:`.expand_tabs`,
76 :attr:`.drop_whitespace`, and :attr:`.replace_whitespace` will have no effect.
77
78 .. versionadded:: 3.4
79
80 .. function:: dedent(text)
81
82 Remove any common leading whitespace from every line in *text*.
83
84 This can be used to make triple-quoted strings line up with the left edge of the
85 display, while still presenting them in the source code in indented form.
86
87 Note that tabs and spaces are both treated as whitespace, but they are not
88 equal: the lines ``" hello"`` and ``"\thello"`` are considered to have no
89 common leading whitespace.
90
91 Lines containing only whitespace are ignored in the input and normalized to a
92 single newline character in the output.
93
94 For example::
95
96 def test():
97 # end first line with \ to avoid the empty line!
98 s = '''\
99 hello
100 world
101 '''
102 print(repr(s)) # prints ' hello\n world\n '
103 print(repr(dedent(s))) # prints 'hello\n world\n'
104
105 .. versionchanged:: 3.14
106 The :func:`!dedent` function now correctly normalizes blank lines containing
107 only whitespace characters. Previously, the implementation only normalized
108 blank lines containing tabs and spaces.
109
110 .. function:: indent(text, prefix, predicate=None)
111
112 Add *prefix* to the beginning of selected lines in *text*.
113
114 Lines are separated by calling ``text.splitlines(True)``.
115
116 By default, *prefix* is added to all lines that do not consist
117 solely of whitespace (including any line endings).
118
119 For example::
120
121 >>> s = 'hello\n\n \nworld'
122 >>> indent(s, ' ')
123 ' hello\n\n \n world'
124
125 The optional *predicate* argument can be used to control which lines
126 are indented. For example, it is easy to add *prefix* to even empty
127 and whitespace-only lines::
128
129 >>> print(indent(s, '+ ', lambda line: True))
130 + hello
131 +
132 +
133 + world
134
135 .. versionadded:: 3.3
136
137
138 :func:`wrap`, :func:`fill` and :func:`shorten` work by creating a
139 :class:`TextWrapper` instance and calling a single method on it. That
140 instance is not reused, so for applications that process many text
141 strings using :func:`wrap` and/or :func:`fill`, it may be more efficient to
142 create your own :class:`TextWrapper` object.
143
144 Text is preferably wrapped on whitespaces and right after the hyphens in
145 hyphenated words; only then will long words be broken if necessary, unless
146 :attr:`TextWrapper.break_long_words` is set to false.
147
148 .. class:: TextWrapper(**kwargs)
149
150 The :class:`TextWrapper` constructor accepts a number of optional keyword
151 arguments. Each keyword argument corresponds to an instance attribute, so
152 for example ::
153
154 wrapper = TextWrapper(initial_indent="* ")
155
156 is the same as ::
157
158 wrapper = TextWrapper()
159 wrapper.initial_indent = "* "
160
161 You can reuse the same :class:`TextWrapper` object many times, and you can
162 change any of its options through direct assignment to instance attributes
163 between uses.
164
165 The :class:`TextWrapper` instance attributes (and keyword arguments to the
166 constructor) are as follows:
167
168
169 .. attribute:: width
170
171 (default: ``70``) The maximum length of wrapped lines. As long as there
172 are no individual words in the input text longer than :attr:`width`,
173 :class:`TextWrapper` guarantees that no output line will be longer than
174 :attr:`width` characters.
175
176
177 .. attribute:: expand_tabs
178
179 (default: ``True``) If true, then all tab characters in *text* will be
180 expanded to spaces using the :meth:`~str.expandtabs` method of *text*.
181
182
183 .. attribute:: tabsize
184
185 (default: ``8``) If :attr:`expand_tabs` is true, then all tab characters
186 in *text* will be expanded to zero or more spaces, depending on the
187 current column and the given tab size.
188
189 .. versionadded:: 3.3
190
191
192 .. attribute:: replace_whitespace
193
194 (default: ``True``) If true, after tab expansion but before wrapping,
195 the :meth:`wrap` method will replace each whitespace character
196 with a single space. The whitespace characters replaced are
197 as follows: tab, newline, vertical tab, formfeed, and carriage
198 return (``'\t\n\v\f\r'``).
199
200 .. note::
201
202 If :attr:`expand_tabs` is false and :attr:`replace_whitespace` is true,
203 each tab character will be replaced by a single space, which is *not*
204 the same as tab expansion.
205
206 .. note::
207
208 If :attr:`replace_whitespace` is false, newlines may appear in the
209 middle of a line and cause strange output. For this reason, text should
210 be split into paragraphs (using :meth:`str.splitlines` or similar)
211 which are wrapped separately.
212
213
214 .. attribute:: drop_whitespace
215
216 (default: ``True``) If true, whitespace at the beginning and ending of
217 every line (after wrapping but before indenting) is dropped.
218 Whitespace at the beginning of the paragraph, however, is not dropped
219 if non-whitespace follows it. If whitespace being dropped takes up an
220 entire line, the whole line is dropped.
221
222
223 .. attribute:: initial_indent
224
225 (default: ``''``) String that will be prepended to the first line of
226 wrapped output. Counts towards the length of the first line. The empty
227 string is not indented.
228
229
230 .. attribute:: subsequent_indent
231
232 (default: ``''``) String that will be prepended to all lines of wrapped
233 output except the first. Counts towards the length of each line except
234 the first.
235
236
237 .. attribute:: fix_sentence_endings
238
239 (default: ``False``) If true, :class:`TextWrapper` attempts to detect
240 sentence endings and ensure that sentences are always separated by exactly
241 two spaces. This is generally desired for text in a monospaced font.
242 However, the sentence detection algorithm is imperfect: it assumes that a
243 sentence ending consists of a lowercase letter followed by one of ``'.'``,
244 ``'!'``, or ``'?'``, possibly followed by one of ``'"'`` or ``"'"``,
245 followed by a space. One problem with this algorithm is that it is
246 unable to detect the difference between "Dr." in ::
247
248 [...] Dr. Frankenstein's monster [...]
249
250 and "Spot." in ::
251
252 [...] See Spot. See Spot run [...]
253
254 :attr:`fix_sentence_endings` is false by default.
255
256 Since the sentence detection algorithm relies on ``string.lowercase`` for
257 the definition of "lowercase letter", and a convention of using two spaces
258 after a period to separate sentences on the same line, it is specific to
259 English-language texts.
260
261
262 .. attribute:: break_long_words
263
264 (default: ``True``) If true, then words longer than :attr:`width` will be
265 broken in order to ensure that no lines are longer than :attr:`width`. If
266 it is false, long words will not be broken, and some lines may be longer
267 than :attr:`width`. (Long words will be put on a line by themselves, in
268 order to minimize the amount by which :attr:`width` is exceeded.)
269
270
271 .. attribute:: break_on_hyphens
272
273 (default: ``True``) If true, wrapping will occur preferably on whitespaces
274 and right after hyphens in compound words, as it is customary in English.
275 If false, only whitespaces will be considered as potentially good places
276 for line breaks, but you need to set :attr:`break_long_words` to false if
277 you want truly insecable words. Default behaviour in previous versions
278 was to always allow breaking hyphenated words.
279
280
281 .. attribute:: max_lines
282
283 (default: ``None``) If not ``None``, then the output will contain at most
284 *max_lines* lines, with *placeholder* appearing at the end of the output.
285
286 .. versionadded:: 3.4
287
288
289 .. index:: single: ...; placeholder
290
291 .. attribute:: placeholder
292
293 (default: ``' [...]'``) String that will appear at the end of the output
294 text if it has been truncated.
295
296 .. versionadded:: 3.4
297
298
299 :class:`TextWrapper` also provides some public methods, analogous to the
300 module-level convenience functions:
301
302 .. method:: wrap(text)
303
304 Wraps the single paragraph in *text* (a string) so every line is at most
305 :attr:`width` characters long. All wrapping options are taken from
306 instance attributes of the :class:`TextWrapper` instance. Returns a list
307 of output lines, without final newlines. If the wrapped output has no
308 content, the returned list is empty.
309
310
311 .. method:: fill(text)
312
313 Wraps the single paragraph in *text*, and returns a single string
314 containing the wrapped paragraph.