Python 'textwrap' 模块在使用 'wrap' 和 'fill' 函数时不替换所有空格

Python 'textwrap' module not replacing all whitespace when using 'wrap' and 'fill' functions

我正在尝试使用 Python textwrap 模块将一些文本输出到控制台。根据 documentationwrapfill 函数默认都会替换空格,因为 replace_witespace kwarg 默认为 True.

然而,在实践中,一些空白仍然存在,我无法根据需要格式化文本。

如何格式化下面的文本,而不是第一句后的大块空格?

Some title
----------

Lorem ipsum dolor sit amet, consectetur adipiscing elit.         Duis sem eros, imperdiet vitae mi
cursus, dapibus fringilla eros. Duis quis euismod ex. Maecenas ac consequat quam. Sed ac augue
dignissim, facilisis sapien vitae, vehicula mi. Maecenas elementum ex eu tortor dignissim
scelerisque. Curabitur et lobortis ex.

这是我正在使用的代码。

from textwrap import fill, wrap

lines = [
    'Some title',
    '----------',
    '',
    ' '.join(wrap('''Lorem ipsum dolor sit amet, consectetur adipiscing elit.
        Duis sem eros, imperdiet vitae mi cursus, dapibus fringilla eros. Duis
        quis euismod ex. Maecenas ac consequat quam. Sed ac augue dignissim,
        facilisis sapien vitae, vehicula mi. Maecenas elementum ex eu tortor
        dignissim scelerisque. Curabitur et lobortis ex.'''))
]
out = []
for l in lines:
    out.append(fill(l, width=100))
print('\n'.join(out))

replace_whitespace 不是常规空格 ' ' - 而只是 '\t\n\v\f\r'.

来自文档:

replace_whitespace (default: True) If true, after tab expansion but before wrapping, the wrap() method will replace each whitespace character with a single space. The whitespace characters replaced are as follows: tab, newline, vertical tab, formfeed, and carriage return ('\t\n\v\f\r').

https://docs.python.org/3/library/textwrap.html#textwrap.TextWrapper.replace_whitespace

所以看起来这可以使用 dedent 并为多行字符串定义单独的字符串来完成。

from textwrap import dedent, fill

lines = [
    'Some title',
    '----------',
    '',
    dedent('Lorem ipsum dolor sit amet, consectetur adipiscing elit. ' \
        'Duis sem eros, imperdiet vitae mi cursus, dapibus fringilla eros. Duis ' \
        'quis euismod ex. Maecenas ac consequat quam. Sed ac augue dignissim, ' \
        'facilisis sapien vitae, vehicula mi. Maecenas elementum ex eu tortor ' \
        'dignissim scelerisque. Curabitur et lobortis ex.')
]
out = []
for l in lines:
    out.append(fill(l, width=100))
print('\n'.join(out))