在大多數情況下,它完成了這項工作,但有時(我很難精確,它依賴於什麼)落入無限循環,因爲它不切分文本字符串。爲什麼在Python( n)中更改字符串中的行不起作用?
def insertNewlines(text, lineLength):
"""
Given text and a desired line length, wrap the text as a typewriter would.
Insert a newline character ("\n") after each word that reaches or exceeds
the desired line length.
text: a string containing the text to wrap.
line_length: the number of characters to include on a line before wrapping
the next word.
returns: a string, with newline characters inserted appropriately.
"""
def spacja(text, lineLength):
return text.find(' ', lineLength-1)
if len(text) <= lineLength:
return text
else:
x = spacja(text, lineLength)
return text[:x] + '\n' + insertNewlines(text[x+1:], lineLength)
作品與我想除了
insertNewlines('Random text to wrap again.', 5)
所有案件和
insertNewlines('mubqhci sixfkt pmcwskvn ikvoawtl rxmtc ehsruk efha cigs itaujqe pfylcoqw iremcty cmlvqjz uzswa ezuw vcsodjk fsjbyz nkhzaoct', 38)
我不知道爲什麼。
也許張貼了insertNewlines將herlp代碼... – ennuikiller 2013-03-17 12:50:27