Python测试包裹替换空白尽管禁用

2024-04-20 12:18:21 发布

您现在位置:Python中文网/ 问答频道 /正文

>>> string
'This contain slashN:\n'
>>> textwrap.wrap(string, 40)
['This contain slashN:']
>>> textwrap.wrap(string, 40, replace_whitespace=False)
['This contain slashN:']
>>>

我期望
['This contain slashN:\n']
为什么textwrap.wrap仍在替换空白(\n这里)? 它的documentation表示:

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

Note

If expand_tabs is false and replace_whitespace is true, each tab character will be replaced by a single space, which is not the same as tab expansion.

Note

If replace_whitespace is false, newlines may appear in the middle of a line and cause strange output. For this reason, text should be split into paragraphs (using str.splitlines() or similar) which are wrapped separately.

编辑:添加我所期望的


Tags: andthetruestringifisthistab
1条回答
网友
1楼 · 发布于 2024-04-20 12:18:21

有一个单独的参数drop_whitespace用于剥离前导空格和尾随空格。它默认为true。传递False以关闭该选项:

>>> textwrap.wrap('This contain slashN:\n', 40, replace_whitespace=False, drop_whitespace=False)
['This contain slashN:\n']

相关问题 更多 >