繁体   English   中英

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

[英]Most efficient way to print pseudo justified text in Python?

假设我有一个字符串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?']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM