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']
添加回答
舉報