2 回答
TA贡献1820条经验 获得超9个赞
这似乎工作正常:
def sms_format(message, size):
result = []
words = message.split()
chunk = words.pop(0)
for word in words:
if len(chunk + word) >= size:
result.append(chunk)
chunk = word
else:
chunk = " ".join((chunk, word))
result.append(chunk)
return result
message = "Your task is to develop a function that takes long text, and splits it into chunks."
print(sms_format(message, 20))
给出:
['Your task is to', 'develop a function', 'that takes long', 'text, and splits it', 'into chunks.']
TA贡献1825条经验 获得超6个赞
更新 elif 块:
elif len(text) > size:
current_size = size
while len(text)>size:
texts = ''.join(text[:current_size])
if texts[-1] == ' ' or text[:size + 1] == ' ':
sms_text.append(texts)
text = text[current_size:]
current_size = size
else:
current_size = current_size - 1
Output : ['Your task is to ', 'develop a function ', 'that takes']
添加回答
举报