>>> 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)?而它的文档说:
replace_whitespace (默认值: True)如果为true,则在选项卡展开后但在包装之前,each ()方法将用单个空格替换每个空格字符。替换的空格字符如下:制表符、换行符、垂直制表符、格式提要和回车('\t\n\v\f\r')。 备注 如果expand_tabs为false,而replace_whitespace为true,则每个制表符字符将被单个空格替换,这与选项卡扩展不同。 备注 如果replace_whitespace为false,则换行符可能出现在行的中间,从而导致奇怪的输出。由于这个原因,文本应该分割成段落(使用str.splitlines()或类似的),这些段落是分开包装的。
编辑:添加我期望的内容
发布于 2016-11-08 05:42:51
有一个单独的参数drop_whitespace用于剥离前导和尾随空格。它默认为true。传递假以关闭它:
>>> textwrap.wrap('This contain slashN:\n', 40, replace_whitespace=False, drop_whitespace=False)
['This contain slashN:\n']https://stackoverflow.com/questions/40479715
复制相似问题