使用textwrap.indent()时第一行的额外空间

时间:2017-10-06 02:41:40

标签: python textwrapping

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.

试着理解为什么在开头的第一行有额外的空间?

1 个答案:

答案 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.
'''