【发布时间】:2014-06-03 06:34:40
【问题描述】:
我想开发一种递归自动换行算法,它采用指定的字符串和换行长度(一行上的最大字符数)来返回输入长度的换行输出。我不希望它分解单词。例如,长度为 20 的 This is the first paragraph that you need to input 返回为:
This is the first
paragraph that you
need to input
但是,我的函数当前打印:
This is the first paragraph
that you need to input
我的代码:
def wrap(text, lineLength):
temp=text.find(" ",lineLength-1)
if temp == -1:
return text
else:
return text[:temp+1]+'\n'+wrap(text[temp+1:], lineLength)
print wrap("This is the first paragraph that you need to input", 20);
为什么这不符合我的预期,我该如何解决?
【问题讨论】:
-
我不知道你是在做这个练习,还是真的在尝试实现它,但 Python 确实有一个模块:docs.python.org/2.7/library/textwrap.html
-
这确实是为了我自己的利益的练习,但我也对内置模块感到好奇。谢谢!
标签: python algorithm recursion word-wrap