使用 textwrap.indent() 时在第一行增加 space

Extra space in the first line when use textwrap.indent()

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.

只是想明白为什么开头的第一行多了一个space?

看看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.
'''