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