textwrap
— Text wrapping and filling文本换行和填充¶
Source code: Lib/textwrap.py
The textwrap
module provides some convenience functions, as well as TextWrapper
, the class that does all the work. textwrap
模块提供了一些方便的函数,以及完成所有工作的类TextWrapper
。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.TextWrapper
实例。
-
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.将单个段落包装在text(字符串)中,使每一行的长度最多为宽度字符。Returns a list of output lines, without final newlines.返回输出行列表,不包含最终换行符。Optional keyword arguments correspond to the instance attributes of可选关键字参数对应于TextWrapper
, documented below.TextWrapper
的实例属性,如下所述。See the有关TextWrapper.wrap()
method for additional details on howwrap()
behaves.wrap()
行为的更多详细信息,请参阅TextWrapper.wrap()
方法。
-
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.将单个段落包装到text中,并返回包含包装段落的单个字符串。fill()
is shorthand for是以下内容的缩写:"\n".join(wrap(text, ...))
In particular,特别是,fill()
accepts exactly the same keyword arguments aswrap()
.fill()
接受与wrap()
完全相同的关键字参数。
-
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.折叠并截断给定的text以适应给定的width。First the whitespace in text is collapsed (all whitespace is replaced by single spaces).首先,text中的空白被折叠(所有空白被单个空格替换)。If the result fits in the width, it is returned.如果结果符合width,则返回结果。Otherwise, enough words are dropped from the end so that the remaining words plus the否则,将从末尾删除足够的单词,以便剩余的单词加上placeholder
fit withinwidth
:placeholder
在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.TextWrapper
的实例属性,如下所述。Note that the whitespace is collapsed before the text is passed to the请注意,在将文本传递给TextWrapper
fill()
function, so changing the value oftabsize
,expand_tabs
,drop_whitespace
, andreplace_whitespace
will have no effect.TextWrapper
fill()
函数之前,空格是折叠的,因此更改tabsize
、expand_tabs
、drop_whitespace
和replace_whitespace
的值将无效。New in version 3.4.版本3.4中新增。
-
textwrap.
dedent
(text)¶ Remove any common leading whitespace from every line in text.删除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." hello"
和"\thello"
行被认为没有公共的前导空白。Lines containing only whitespace are ignored in the input and normalized to a single newline character in the output.在输入中忽略仅包含空格的行,并在输出中归一化为单个换行符。For example:例如: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'
-
textwrap.
indent
(text, prefix, predicate=None)¶ Add prefix to the beginning of selected lines in text.在text中选定行的开头添加prefix。Lines are separated by calling通过调用text.splitlines(True)
.text.splitlines(True)
分隔行。By default, prefix is added to all lines that do not consist solely of whitespace (including any line endings).默认情况下,prefix添加到不完全由空格组成的所有行(包括任何行尾)。For example:例如:>>> 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.可选predicate参数可用于控制缩进的行。For example, it is easy to add prefix to even empty and whitespace-only lines:例如,很容易将prefix添加到空行和纯空白行:>>> print(indent(s, '+ ', lambda line: True))
+ hello
+
+
+ worldNew in version 3.3.版本3.3中新增。
wrap()
, fill()
and shorten()
work by creating a TextWrapper
instance and calling a single method on it. wrap()
、fill()
和shorten()
通过创建TextWrapper
实例并对其调用单个方法来工作。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.wrap()
和/或fill()
处理许多文本字符串的应用程序,创建自己的TextWrapper
对象可能更有效。
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.TextWrapper.break_long_words
设置为false
,否则只有这样,长单词才会在必要时被打断。
-
class
textwrap.
TextWrapper
(**kwargs)¶ TheTextWrapper
constructor accepts a number of optional keyword arguments.TextWrapper
构造函数接受许多可选的关键字参数。Each keyword argument corresponds to an instance attribute, so for example每个关键字参数对应一个实例属性,例如wrapper = TextWrapper(initial_indent="* ")
is the same as与相同wrapper = TextWrapper()
wrapper.initial_indent = "* "You can re-use the same您可以多次重复使用同一TextWrapper
object many times, and you can change any of its options through direct assignment to instance attributes between uses.TextWrapper
对象,并且可以通过在使用之间直接分配实例属性来更改其任何选项。TheTextWrapper
instance attributes (and keyword arguments to the constructor) are as follows:TextWrapper
实例属性(和构造函数的关键字参数)如下所示:-
width
¶ (default:(默认值:70
) The maximum length of wrapped lines.70
)包裹线的最大长度。As long as there are no individual words in the input text longer than只要输入文本中没有超过width
,TextWrapper
guarantees that no output line will be longer thanwidth
characters.width
个单个单词,TextWrapper
就保证输出行不会超过width
个字符。
-
expand_tabs
¶ (default:(默认值:True
) If true, then all tab characters in text will be expanded to spaces using theexpandtabs()
method of text.True
)如果为True
,则使用text的expandtabs()
方法将文本中的所有制表符扩展为空格。
-
tabsize
¶ (default:(默认值:8
)8
)If如果expand_tabs
is true, then all tab characters in text will be expanded to zero or more spaces, depending on the current column and the given tab size.expand_tabs
为true
,则text中的所有制表符将扩展到零个或更多空格,具体取决于当前列和给定的制表符大小。New in version 3.3.版本3.3中新增。
-
replace_whitespace
¶ (default:(默认值:True
) If true, after tab expansion but before wrapping, thewrap()
method will replace each whitespace character with a single space.True
)如果为True
,则在展开制表符后但换行之前,wrap()
方法将用单个空格替换每个空白字符。The whitespace characters replaced are as follows: tab, newline, vertical tab, formfeed, and carriage return (替换的空白字符如下:制表符、换行符、垂直制表符、换行符和回车符('\t\n\v\f\r'
).'\t\n\v\f\r'
)。Note
If如果expand_tabs
is false andreplace_whitespace
is true, each tab character will be replaced by a single space, which is not the same as tab expansion.expand_tabs
为false
,replace_whitespace
为true
,则每个制表符将替换为单个空格,这与制表符扩展不同。Note
If如果replace_whitespace
is false, newlines may appear in the middle of a line and cause strange output.replace_whitespace
为false
,则换行符可能出现在行的中间,并导致奇怪的输出。For this reason, text should be split into paragraphs (using因此,应将文本拆分为单独包装的段落(使用str.splitlines()
or similar) which are wrapped separately.str.splitlines()
或类似内容)。
-
drop_whitespace
¶ (default:(默认值:True
) If true, whitespace at the beginning and ending of every line (after wrapping but before indenting) is dropped.True
)如果为True
,则删除每行开头和结尾处的空格(换行后但缩进前)。Whitespace at the beginning of the paragraph, however, is not dropped if non-whitespace follows it.但是,如果后面有非空格,则不会删除段落开头的空格。If whitespace being dropped takes up an entire line, the whole line is dropped.如果删除的空格占用整行,则整行将被删除。
-
initial_indent
¶ (default:(默认值:''
) String that will be prepended to the first line of wrapped output.''
)字符串,该字符串将前置到包装输出的第一行。Counts towards the length of the first line. The empty string is not indented.计算第一行的长度。空字符串未缩进。
-
subsequent_indent
¶ (default:(默认值:''
) String that will be prepended to all lines of wrapped output except the first. Counts towards the length of each line except the first.''
)字符串,该字符串将前置到除第一行外的所有包装输出行。除第一行外,按每行的长度计算。
-
fix_sentence_endings
¶ (default:(默认值:False
) If true,TextWrapper
attempts to detect sentence endings and ensure that sentences are always separated by exactly two spaces.False
)如果为true
,TextWrapper
将尝试检测句子结尾,并确保句子始终由恰好两个空格分隔。This is generally desired for text in a monospaced font.这通常适用于等距字体中的文本。However, the sentence detection algorithm is imperfect: it assumes that a sentence 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 is algorithm is that it is unable to detect the difference between “Dr.” in这种算法的一个问题是,它无法检测中“Dr.”之间的差异[...] Dr. Frankenstein's monster [...]
and “Spot.” in并且“Spot.”在里面[...] See Spot. See Spot run [...]
fix_sentence_endings
is false by default.默认情况下为false
。Since the sentence detection algorithm relies on由于句子检测算法依赖于string.lowercase
for the definition of “lowercase letter”, and a convention of using two spaces after a period to separate sentences on the same line, it is specific to English-language texts.string.lowercase
来定义“小写字母”,以及在一个句点后使用两个空格在同一行上分隔句子的约定,因此它特定于英语文本。
-
break_long_words
¶ (default:(默认值:True
) If true, then words longer thanwidth
will be broken in order to ensure that no lines are longer thanwidth
.True
)如果为True
,则将打断长于width
的文字,以确保没有行长于width
。If it is false, long words will not be broken, and some lines may be longer than如果为width
.false
,则长单词不会被打断,并且某些行可能比width
长。(Long words will be put on a line by themselves, in order to minimize the amount by which(长单词将自己放在一行上,以尽量减少超出width
is exceeded.)width
的数量。)
-
break_on_hyphens
¶ (default:(默认值:True
) If true, wrapping will occur preferably on whitespaces and right after hyphens in compound words, as it is customary in English.True
)如果为True
,则在复合词中,换行符最好出现在空白处和连字符后面,这在英语中是惯例。If false, only whitespaces will be considered as potentially good places for line breaks, but you need to set如果为break_long_words
to false if you want truly insecable words.false
,则只有空格才被视为可能适合换行的位置,但如果您想要真正不安全的单词,则需要将break_long_words
设置为false
。Default behaviour in previous versions was to always allow breaking hyphenated words.以前版本中的默认行为是始终允许断开连字符。
-
max_lines
¶ (default:(默认值:None
) If notNone
, then the output will contain at most max_lines lines, with placeholder appearing at the end of the output.None
)如果不是None
,则输出最多包含max_lines行,placeholder出现在输出的末尾。New in version 3.4.版本3.4中新增。
-
placeholder
¶ (default:(默认值:' [...]'
) String that will appear at the end of the output text if it has been truncated.' [...]'
)如果输出文本被截断,则将显示在其末尾的字符串。New in version 3.4.版本3.4中新增。
TextWrapper
also provides some public methods, analogous to the module-level convenience functions:还提供了一些公共方法,类似于模块级便利功能:-
wrap
(text)¶ Wraps the single paragraph in text (a string) so every line is at most将单个段落包装在text(字符串)中,使每一行的长度最多为width
characters long.width
字符。All wrapping options are taken from instance attributes of the所有包装选项都取自TextWrapper
instance.TextWrapper
实例的实例属性。Returns a list of output lines, without final newlines.返回输出行列表,不包含最终换行符。If the wrapped output has no content, the returned list is empty.如果包装的输出没有内容,则返回的列表为空。
-
fill
(text)¶ Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph.将单个段落包装到text中,并返回包含包装段落的单个字符串。
-