gpt4 book ai didi

python - 在Python中打印伪对齐文本的最有效方法?

转载 作者:行者123 更新时间:2023-12-01 02:06:31 25 4
gpt4 key购买 nike

假设我有一个字符串 s,其中有很多用空格分隔的单词。现在假设我想打印这个字符串,分布在几行上(也就是说,一些单词之间应该定期有一个换行符),以便每行的字符数大致相等(不必须完全相等,各处可能存在微小差异。执行此操作的最有效方法是什么(在代码行和运行时间方面)?

我意识到我可以每隔一定数量的字符插入一个换行符,但这可能会以不期望的方式分割单词,因此这是 Not Acceptable 。我之所以问这个问题,是因为我知道在 Java 中,字符串是不可变的,因此一次构建一个字符的字符串的时间复杂度为 O(n^2)。有人有什么聪明的主意吗?

最佳答案

您正在寻找textwrap.wrap :

textwrap.wrap(text, width=70, **kwargs)

Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.

演示:

>>> import textwrap
>>> textwrap.wrap(s)
['Suppose I have a string s with plenty of words separated by spaces.',
'Now suppose I wanted to print this string spread out across several',
'lines (that is, there should be a newline character periodically in',
'between some of the words) so that each of the lines is approximately',
"equal in number of characters per line (doesn't have to be exactly",
'equal, there could be small variances here and there. What would be',
'the most efficient way of doing this (in both lines of code and',
'running time)? I realize I could insert a newline character every',
'certain number of characters but this might slit the word in an',
'undesirable way so that is not acceptable. The reason I ask is because',
'I know in Java, strings are immutable and thus building a string one',
'character at a time is O(n^2). Anyone got any clever ideas?']

关于python - 在Python中打印伪对齐文本的最有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48999628/

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