gpt4 book ai didi

python - 自动换行算法未按预期打印

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:37:10 26 4
gpt4 key购买 nike

我想开发一种递归自动换行算法,它采用指定的字符串和换行长度(一行中的最大字符数)返回输入长度的换行输出。我不希望它分解单词。例如,This is the first paragraph that you need to input with length 20 returns as:

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);

为什么这没有按照我的预期进行,我该如何解决?

最佳答案

通过一些更改您的代码可以工作:

def wrap(text, lineLength):
if len(text) <= lineLength: return text
temp = text.rfind(" ", 0, lineLength - 1)
if temp == -1:
return text
else:
return text[:temp+1]+'\n'+wrap(text[temp+1:], lineLength)

有了这个输出:

This is the first 
paragraph that you
need to input

但您可能还想在没有空格可分隔时强制使用连字符:

def wrap(text, lineLength):
if len(text) <= lineLength: return text
temp = text.rfind(" ", 0, lineLength - 1)
if temp == -1:
return text[:lineLength - 1] + '-\n' + wrap(
text[lineLength - 1:], lineLength)
else:
return text[:temp+1] + '\n' + wrap(text[temp+1:], lineLength)

print wrap("Thisisthefirstparagraphthatyouneed to input", 20)

这导致:

Thisisthefirstparag-
raphthatyouneed to
input

关于python - 自动换行算法未按预期打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24008531/

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