首页 > 解决方案 > 两个多行字符串的水平连接

问题描述

我目前尝试水平连接两个多行字符串。例如,有两个字符串 str_a 和 str_b

str_a = """This is row \nAnd this is row\nThis is the final row"""
str_b = """A\nB"""

随着打印返回

This is row 
And this is row 
This is the final row 

A
B

水平连接后结果字符串的打印返回应如下所示

This is row A
And this is row B
This is the final row

标签: pythonstring

解决方案


用这个:

import itertools

for a, b in itertools.zip_longest(str_a.split('\n'), str_b.split('\n')):
    print(a, b if b else '')

输出:

This is row  A
And this is row B
This is the final row 

推荐阅读