sample_text = '''
The textwrap module can be used to format text for output in
situations where pretty-printing is desired. It offers
programmatic functionality similar to the paragraph wrapping
or filling features found in many text editors.
'''
dedented_text = textwrap.dedent(sample_text)
wrapped = textwrap.fill(dedented_text, width=50)
final = textwrap.indent(wrapped, '> ')
print('Quoted block:\n')
print(final)
输出是:
> The textwrap module can be used to format text
> for output in situations where pretty-printing is
> desired. It offers programmatic functionality
> similar to the paragraph wrapping or filling
> features found in many text editors.
试着理解为什么在开头的第一行有额外的空间?
答案 0 :(得分:4)
看看repr(sample_text)
:
'\n The textwrap module can be used to format text for output in\n situations where pretty-printing is desired. It offers\n programmatic functionality similar to the paragraph wrapping\n or filling features found in many text editors.\n '
注意开头的\n
?
要获得所需的输出,您必须逃避它。将\
放在字符串的开头:
sample_text = '''\
The textwrap module can be used to format text for output in
situations where pretty-printing is desired. It offers
programmatic functionality similar to the paragraph wrapping
or filling features found in many text editors.
'''