textwrap --- 文字包裝與填充¶
原始碼:Lib/textwrap.py
The textwrap module provides some convenience functions,
as well as TextWrapper, the class that does all the work.
If you're just wrapping or filling one or two text strings, the convenience
functions should be good enough; otherwise, you should use an instance of
TextWrapper for efficiency.
- textwrap.wrap(text, width=70, *, initial_indent='', subsequent_indent='', expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True, tabsize=8, max_lines=None, placeholder=' [...]')¶
Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.
Optional keyword arguments correspond to the instance attributes of
TextWrapper, documented below.See the
TextWrapper.wrap()method for additional details on howwrap()behaves.
- textwrap.fill(text, width=70, *, initial_indent='', subsequent_indent='', expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True, tabsize=8, max_lines=None, placeholder=' [...]')¶
Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph.
fill()is shorthand for"\n".join(wrap(text, ...))
In particular,
fill()accepts exactly the same keyword arguments aswrap().
- textwrap.shorten(text, width, *, fix_sentence_endings=False, break_long_words=True, break_on_hyphens=True, placeholder=' [...]')¶
Collapse and truncate the given text to fit in the given width.
First the whitespace in text is collapsed (all whitespace is replaced by single spaces). If the result fits in the width, it is returned. Otherwise, enough words are dropped from the end so that the remaining words plus the placeholder fit within width:
>>> textwrap.shorten("Hello world!", width=12) 'Hello world!' >>> textwrap.shorten("Hello world!", width=11) 'Hello [...]' >>> textwrap.shorten("Hello world", width=10, placeholder="...") 'Hello...'
Optional keyword arguments correspond to the instance attributes of
TextWrapper, documented below. Note that the whitespace is collapsed before the text is passed to theTextWrapperfill()function, so changing the value oftabsize,expand_tabs,drop_whitespace, andreplace_whitespacewill have no effect.在 3.4 版被加入.
- textwrap.dedent(text)¶
Remove any common leading whitespace from every line in text.
This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form.
Note that tabs and spaces are both treated as whitespace, but they are not equal: the lines
" hello"and"\thello"are considered to have no common leading whitespace.Lines containing only whitespace are ignored in the input and normalized to a single newline character in the output.
舉例來說:
def test(): # end first line with \ to avoid the empty line! s = '''\ hello world ''' print(repr(s)) # prints ' hello\n world\n ' print(repr(dedent(s))) # prints 'hello\n world\n'
在 3.14 版的變更: The
dedent()function now correctly normalizes blank lines containing only whitespace characters. Previously, the implementation only normalized blank lines containing tabs and spaces.
- textwrap.indent(text, prefix, predicate=None)¶
Add prefix to the beginning of selected lines in text.
Lines are separated by calling
text.splitlines(True).By default, prefix is added to all lines that do not consist solely of whitespace (including any line endings).
舉例來說:
>>> s = 'hello\n\n \nworld' >>> indent(s, ' ') ' hello\n\n \n world'
The optional predicate argument can be used to control which lines are indented. For example, it is easy to add prefix to even empty and whitespace-only lines:
>>> print(indent(s, '+ ', lambda line: True)) + hello + + + world
在 3.3 版被加入.
wrap(), fill() and shorten() work by creating a
TextWrapper instance and calling a single method on it. That
instance is not reused, so for applications that process many text
strings using wrap() and/or fill(), it may be more efficient to
create your own TextWrapper object.
Text is preferably wrapped on whitespaces and right after the hyphens in
hyphenated words; only then will long words be broken if necessary, unless
TextWrapper.break_long_words is set to false.
- class textwrap.TextWrapper(**kwargs)¶
The
TextWrapperconstructor accepts a number of optional keyword arguments. Each keyword argument corresponds to an instance attribute, so for examplewrapper = TextWrapper(initial_indent="* ")
is the same as
wrapper = TextWrapper() wrapper.initial_indent = "* "
You can reuse the same
TextWrapperobject many times, and you can change any of its options through direct assignment to instance attributes between uses.The
TextWrapperinstance attributes (and keyword arguments to the constructor) are as follows:- width¶
(default:
70) The maximum length of wrapped lines. As long as there are no individual words in the input text longer than