Python函数消息格式化程序

我的任务是开发一个函数,该函数接收字符串消息并在需要时返回带有分页的字符串消息数组。对于本练习,输入消息中的最大字符数为 160。此外,不要将单词分成音节和连字符。


我的功能没有满足不分词的功能


def sms_format(message, size):

    sms_text = []

    if len(message) == 0:

        return sms_text


    text = list(message)


    if len(text) <= size:

        new_text = ''.join(text)

        sms_text.append(new_text)


    elif len(text) > size:

        while len(text)>size:

            texts = ''.join(text[:size])

            sms_text.append(texts)

            text = text[size:]


        sms_text.append(''.join(text))


    return(sms_text)



message = "Your task is to develop a function that takes"



print(sms_format(message, 20))


实际结果: ['Your task is to deve', 'lop a function that ', 'takes']


预期结果:它不应该破坏单词


SMILET
浏览 154回答 2
2回答

慕妹3146593

这似乎工作正常:def sms_format(message, size):&nbsp; &nbsp; result = []&nbsp; &nbsp; words = message.split()&nbsp; &nbsp; chunk = words.pop(0)&nbsp; &nbsp; for word in words:&nbsp; &nbsp; &nbsp; &nbsp; if len(chunk + word) >= size:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.append(chunk)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; chunk = word&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; chunk = " ".join((chunk, word))&nbsp; &nbsp; result.append(chunk)&nbsp; &nbsp; return resultmessage = "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.']

胡子哥哥

更新 elif 块:elif len(text) > size:&nbsp; &nbsp; &nbsp; &nbsp; current_size = size&nbsp; &nbsp; &nbsp; &nbsp; while len(text)>size:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; texts = ''.join(text[:current_size])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if texts[-1] == ' ' or text[:size + 1] == ' ':&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sms_text.append(texts)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; text = text[current_size:]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; current_size = size&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; current_size = current_size - 1Output : ['Your task is to ', 'develop a function ', 'that takes']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python