textwrap --- 文字包裝與填充

原始碼:Lib/textwrap.py


Thetextwrap module provides some convenience functions,as well asTextWrapper, the class that does all the work.If you're just wrapping or filling one or two text strings, the conveniencefunctions should be good enough; otherwise, you should use an instance ofTextWrapper 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 intext (a string) so every line is at mostwidth characters long. Returns a list of output lines, without finalnewlines.

Optional keyword arguments correspond to the instance attributes ofTextWrapper, documented below.

See theTextWrapper.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 intext, and returns a single string containing thewrapped 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 giventext to fit in the givenwidth.

First the whitespace intext is collapsed (all whitespace is replaced bysingle spaces). If the result fits in thewidth, it is returned.Otherwise, enough words are dropped from the end so that the remaining wordsplus theplaceholder fit withinwidth:

>>>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 ofTextWrapper, documented below. Note that the whitespace iscollapsed before the text is passed to theTextWrapperfill()function, so changing the value oftabsize,expand_tabs,drop_whitespace, andreplace_whitespace will have no effect.

在 3.4 版被加入.

textwrap.dedent(text)

Remove any common leading whitespace from every line intext.

This can be used to make triple-quoted strings line up with the left edge of thedisplay, while still presenting them in the source code in indented form.

Note that tabs and spaces are both treated as whitespace, but they are notequal: the lines" hello" and"\thello" are considered to have nocommon leading whitespace.

Lines containing only whitespace are ignored in the input and normalized to asingle newline character in the output.

舉例來說:

deftest():# 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'
textwrap.indent(text,prefix,predicate=None)

Addprefix to the beginning of selected lines intext.

Lines are separated by callingtext.splitlines(True).

By default,prefix is added to all lines that do not consistsolely of whitespace (including any line endings).

舉例來說:

>>>s='hello\n\n\nworld'>>>indent(s,'  ')'  hello\n\n \n  world'

The optionalpredicate argument can be used to control which linesare indented. For example, it is easy to addprefix to even emptyand whitespace-only lines:

>>>print(indent(s,'+ ',lambdaline:True))+ hello+++ world

在 3.3 版被加入.

wrap(),fill() andshorten() work by creating aTextWrapper instance and calling a single method on it. Thatinstance is not reused, so for applications that process many textstrings usingwrap() and/orfill(), it may be more efficient tocreate your ownTextWrapper object.

Text is preferably wrapped on whitespaces and right after the hyphens inhyphenated words; only then will long words be broken if necessary, unlessTextWrapper.break_long_words is set to false.

classtextwrap.TextWrapper(**kwargs)

TheTextWrapper constructor accepts a number of optional keywordarguments. Each keyword argument corresponds to an instance attribute, sofor example

wrapper=TextWrapper(initial_indent="* ")

is the same as

wrapper=TextWrapper()wrapper.initial_indent="* "

You can reuse the sameTextWrapper object many times, and you canchange any of its options through direct assignment to instance attributesbetween uses.

TheTextWrapper instance attributes (and keyword arguments to theconstructor) are as follows:

width

(default:70) The maximum length of wrapped lines. As long as thereare no individual words in the input text longer thanwidth,TextWrapper guarantees that no output line will be longer thanwidth characters.

expand_tabs

(default:True) If true, then all tab characters intext will beexpanded to spaces using theexpandtabs() method oftext.

tabsize

(default:8) Ifexpand_tabs is true, then all tab charactersintext will be expanded to zero or more spaces, depending on thecurrent column and the given tab size.

在 3.3 版被加入.

replace_whitespace

(default:True) If true, after tab expansion but before wrapping,thewrap() method will replace each whitespace characterwith a single space. The whitespace characters replaced areas follows: tab, newline, vertical tab, formfeed, and carriagereturn ('\t\n\v\f\r').

備註

Ifexpand_tabs is false andreplace_whitespace is true,each tab character will be replaced by a single space, which isnotthe same as tab expansion.

備註

Ifreplace_whitespace is false, newlines may appear in themiddle of a line and cause strange output. For this reason, text shouldbe split into paragraphs (usingstr.splitlines() or similar)which are wrapped separately.

drop_whitespace

(default:True) If true, whitespace at the beginning and ending ofevery line (after wrapping but before indenting) is dropped.Whitespace at the beginning of the paragraph, however, is not droppedif non-whitespace follows it. If whitespace being dropped takes up anentire line, the whole line is dropped.

initial_indent

(default:'') String that will be prepended to the first line ofwrapped output. Counts towards the length of the first line. The emptystring is not indented.

subsequent_indent

(default:'') String that will be prepended to all lines of wrappedoutput except the first. Counts towards the length of each line exceptthe first.

fix_sentence_endings

(default:False) If true,TextWrapper attempts to detectsentence endings and ensure that sentences are always separated by exactlytwo spaces. This is generally desired for text in a monospaced font.However, the sentence detection algorithm is imperfect: it assumes that asentence ending consists of a lowercase letter followed by one of'.','!', or'?', possibly followed by one of'"' or"'",followed by a space. One problem with this algorithm is that it isunable to detect the difference between "Dr." in

[...]Dr.Frankenstein's monster [...]

and "Spot." in

[...]SeeSpot.SeeSpotrun[...]

fix_sentence_endings is false by default.

Since the sentence detection algorithm relies onstring.lowercase forthe definition of "lowercase letter", and a convention of using two spacesafter a period to separate sentences on the same line, it is specific toEnglish-language texts.

break_long_words

(default:True) If true, then words longer thanwidth will bebroken in order to ensure that no lines are longer thanwidth. Ifit is false, long words will not be broken, and some lines may be longerthanwidth. (Long words will be put on a line by themselves, inorder to minimize the amount by whichwidth is exceeded.)

break_on_hyphens

(default:True) If true, wrapping will occur preferably on whitespacesand right after hyphens in compound words, as it is customary in English.If false, only whitespaces will be considered as potentially good placesfor line breaks, but you need to setbreak_long_words to false ifyou want truly insecable words. Default behaviour in previous versionswas to always allow breaking hyphenated words.

max_lines

(default:None) If notNone, then the output will contain at mostmax_lines lines, withplaceholder appearing at the end of the output.

在 3.4 版被加入.

placeholder

(default:'[...]') String that will appear at the end of the outputtext if it has been truncated.

在 3.4 版被加入.

TextWrapper also provides some public methods, analogous to themodule-level convenience functions:

wrap(text)

Wraps the single paragraph intext (a string) so every line is at mostwidth characters long. All wrapping options are taken frominstance attributes of theTextWrapper instance. Returns a listof output lines, without final newlines. If the wrapped output has nocontent, the returned list is empty.

fill(text)

Wraps the single paragraph intext, and returns a single stringcontaining the wrapped paragraph.