假设我有一个字符串s,其中有许多单词用空格分隔。现在,假设我想打印散布在多行中的字符串(也就是说,在某些单词之间应该定期有换行符),以便每行的行数大约等于每行的字符数(不是必须完全相等,这里和那里可能会有很小的差异,这样做的最有效方法是什么(在代码行和运行时间上)?

我意识到我可以每隔一定数量的字符插入一个换行符,但这可能会以不希望的方式将单词分割开,因此是不可接受的。我问的原因是因为我在Java中知道字符串是不可变的,因此一次构建一个字符的字符串为O(n ^ 2)。有人有什么聪明的主意吗?

最佳答案

您正在寻找textwrap.wrap

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



  将单个段落包装为文本(字符串),因此每行最多为宽度字符长。返回输出行列表,不带最终换行符。


演示:

>>> 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/

10-12 22:43