我有一个长字符串:
S='Hello\n i have a very very very very..... very very very very.... long Text!'
打印此文本会产生一长行,我想将该行分成最大长度为 10 或 20 个字符的片段。我想用 \n
换行,并将 \n
包含在新字符串中。
我的期望:
Hello
i have a very
very very very
..... very very
very very....
long Text!
最佳答案
textwrap.wrap
允许您将字符串包装到特定的宽度
。
默认情况下,它在换行之前用单个空格替换空格,包括换行符。
如果你想保留换行等,设置replace_whitespace=False
>>> import textwrap
>>> s = 'Hello\n i have a very very very very..... very very very very.... long Text!'
>>> print('\n'.join(textwrap.wrap(s, width=20, replace_whitespace=False)))
Hello
i have a very
very very very.....
very very very
very.... long Text!
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.
https://stackoverflow.com/questions/42002918/
相关文章:
amazon-dynamodb - DynamoDB PutItem 然后 UpdateItem 与
node.js - 如何让 Heroku 运行子文件夹中的 Node 应用程序?
excel - 如何根据时间应用 WorksheetFunction.CountIfs?
javascript - 在javascript中将对象作为参数传递的性能
Angular 2 - 如何将响应式(Reactive)表单元素动态绑定(bind)到事件?
wordpress - 如何禁用 Wordpress/Woocommerce 中的自动 https
python-3.x - 无法将音频上传到 Telegram 错误请求 : failed to ge