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

Python实现多行字符串按行对应拼接(支持多字符串输入)

多行字符串横向拼接的Python实现

需求说明

需要将多个多行字符串横向对齐拼接:每个字符串的对应行上下对齐,第一行用指定分隔符连接,其余行保持位置对齐,避免常规拼接导致的纵向堆叠问题。

简单示例

输入:

s1 = "a\nb\nc"
s2 = "d\ne\nf"

常规拼接s1 + "->" + s2输出:

a
b
c->d
e
f

期望输出:

a->d
b  e
c  f

多字符串示例

输入列表:

DT = [
    'Parents\n|\n|\n|\n|---> Yes ---> Cinema',
    'No',
    'Weather\n|\n|\n|---> Sunny ---> Tennis\n|\n|---> Rainy --> Cinema',
    'Windy',
    'Money\n|\n|\n|---> Rich ---> Cinema\n|\n|---> Poor ---> Cinema',
    'No',
    'Windy'
]

期望输出:

Parents ---> No ---> Weather ---> Windy ---> Money ---> No ---> Windy
 |                    |                       |                    |
 |                    |                       |                    |
 |                    |                       |                    |
|---> Yes ---> Cinema|                       |                    |
                      |---> Sunny ---> Tennis|                    |
                      |                       |---> Rich ---> Cinema|
                      |---> Rainy --> Cinema |                    |
                      |                       |---> Poor ---> Cinema|

实现代码

def horizontal_concat(strings, sep=" ---> "):
    # 将每个字符串拆分成行列表
    line_lists = [s.split('\n') for s in strings]
    # 记录每列的宽度(以对应字符串的第一行长度为准)
    col_widths = [len(lines[0]) for lines in line_lists]
    # 计算所有字符串中的最大行数
    max_lines = max(len(lines) for lines in line_lists)
    
    # 补全行列表,确保每个列表长度等于最大行数,不足部分用空字符串填充
    padded_lines = [lines + [''] * (max_lines - len(lines)) for lines in line_lists]
    
    result = []
    # 处理第一行:用指定分隔符连接各列的第一行
    result.append(sep.join(line[0] for line in padded_lines))
    
    # 处理剩余行:按列宽对齐,列之间用与分隔符等长的空格填充
    sep_spaces = ' ' * len(sep)
    for line_idx in range(1, max_lines):
        current_parts = []
        for col_idx in range(len(padded_lines)):
            # 当前列的内容左对齐到列宽
            aligned_content = padded_lines[col_idx][line_idx].ljust(col_widths[col_idx])
            current_parts.append(aligned_content)
            # 非最后一列添加空格分隔
            if col_idx != len(padded_lines) - 1:
                current_parts.append(sep_spaces)
        # 拼接并去除末尾多余空格
        full_line = ''.join(current_parts).rstrip()
        result.append(full_line)
    
    return '\n'.join(result)

# 测试简单示例
s1 = "a\nb\nc"
s2 = "d\ne\nf"
print(horizontal_concat([s1, s2], sep="->"))
print("\n" + "-"*20 + "\n")

# 测试多字符串示例
DT = [
    'Parents\n|\n|\n|\n|---> Yes ---> Cinema',
    'No',
    'Weather\n|\n|\n|---> Sunny ---> Tennis\n|\n|---> Rainy --> Cinema',
    'Windy',
    'Money\n|\n|\n|---> Rich ---> Cinema\n|\n|---> Poor ---> Cinema',
    'No',
    'Windy'
]
print(horizontal_concat(DT))

代码说明

  1. 拆分与补全:将每个字符串按换行分割为行列表,补全所有列表到最大行数,避免索引越界。
  2. 列宽计算:以每个字符串的第一行长度作为对应列的宽度,保证后续行对齐。
  3. 第一行处理:直接用指定分隔符连接各列的第一行。
  4. 剩余行处理:将每行内容左对齐到对应列宽,列之间用与分隔符等长的空格填充,确保横向位置对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:35:16