python函数将消息分成n行

2024-04-19 02:34:29 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么每个人,我想做这样的事情,但我的逻辑不是那么愚蠢。我有一个信息,每行必须80个字符:我可以这样做:

msg = ''
msg_list = []

for i in dict['msg']:
    if len(msg) >= 80 and i.isspace():
    msg_list.append(msg)
    msg = "" 

    msg += i

这里的问题是,当我的味精没有80个字符,有什么办法让这个块更好地工作?你知道吗


Tags: andin信息forlenifmsg逻辑
3条回答

检查第80个字符。如果这是一个空间,你可以打破线。如果没有,检查79号。冲洗。重复

假设你在76岁时破产了。现在检查第(76+80)个字符是否是空格。等等等等。你知道吗

如果你不能把这变成代码,张贴你的最佳尝试,我们可以从那里提出建议。你知道吗

而且,for i in dict['msg']:没有意义。是否重新定义了内置的dict类型?你知道吗

import textwrap
msg_list = textwrap.wrap(dict['msg'], 80)
import re

input = "put your text in here"
tokens = re.split('\s', input)

w = []
s = ""
for token in tokens:
    if len(s) + len(token) < 80:
        s = " ".join([s,token])
    else:
        w.append(s)
        s = ""
print w

相关问题 更多 >