You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

文本对齐(text justification)问题:实现交替对齐的聊天会话展示效果

聊天会话文本对齐功能修复方案

核心问题

你的代码存在两处核心错误导致输出不符合预期:

  • 输出逻辑未遵循消息时序:你将用户1、用户2的拆分后内容分别存入两个独立列表,先全量打印用户1的所有消息,再打印用户2的所有消息,完全打乱了原消息的发送顺序
  • 长文本拆分逻辑存在bug:处理单行剩余字符的逻辑错误,甚至会误操作对方用户的消息数组,导致文本拆分结果异常

修复后完整代码

messages = [["1", "Bob hello"], ["2", "Alice hi"], ["1", "How is your life"], ["1", "Better than before"],
            ["2", "M super"], ["1", "Wow pro"]]
userWidth = 6
width = 15

def chat(messages, userWidth, width):
    # 存储时序化的消息行数据,每个元素格式为(用户标识, 行内容)
    line_queue = []
    for user, convo in messages:
        # 按userWidth长度拆分文本
        for i in range(0, len(convo), userWidth):
            line_content = convo[i:i+userWidth]
            line_queue.append((user, line_content))
    # 按顺序输出
    for user, content in line_queue:
        if user == "1":
            # 用户1左对齐,左侧加|,右侧补空格
            pad_space = width - 1 - len(content)
            print(f"|{content}{' ' * pad_space}")
        else:
            # 用户2右对齐,右侧加|,左侧补空格
            pad_space = width - 1 - len(content)
            print(f"{' ' * pad_space}{content}|")

chat(messages, userWidth, width)

输出效果

|Bob he         
|llo            
        Alice |
           hi|
|How is         
|your l         
|ife           
|Better         
|than b         
|efore         
          M sup|
             er|
|Wow pro       

内容的提问来源于stack exchange,提问作者bloomsdayforever

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 14:09:03