gpt4 book ai didi

python - 在 Python 中自动换行打印字符串

转载 作者:行者123 更新时间:2023-12-05 08:11:58 30 4
gpt4 key购买 nike

我有一个长字符串:

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.

关于python - 在 Python 中自动换行打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42002918/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com