我正在尝试连接跨多行的数据。我不会告诉你这些数据来自哪里,但它不会混淆水域,但它是一个字符串的形式,样本可能是这样的:
aaa + bbb = aaabbb
aaa + bbb = aaabbb
aaa + bbb = aaabbb
我在下面做了一些简单的演示代码:
a = "next\nnext\nnext"
b = "text\ntext\ntext"
c = a,b
c = ','.join(c[0:2])
print c
预期输出:
next,text
next,text
next,text
但我要打印的内容如下:
next
next
next,text
text
text
我不确定我是否刚刚选择了构建一些多行代码的错误方法,或者我的代码不正确,但不管怎样,有人可以提出一种方法来获得所需的输出格式:
aaabbb
aaabbb
aaabbb
由于
答案 0 :(得分:3)
a = "next\nnext\nnext"
b = "text\ntext\ntext"
print("\n".join([",".join(x) for x in zip(a.split(),b.split()))])
next,text
next,text
next,text
拆分换行,拉链然后重新加入。
# ele 0 from a is grouped with ele 0 from b etc..
In [15]: zip(a.split(),b.split())
Out[15]: [('next', 'text'), ('next', 'text'), ('next', 'text')]
# then we rejoin as one string the elements in the tuples ('next', 'text') -> 'next,text'
In [18]: [",".join(x) for x in zip(a.split(),b.split())]
Out[18]: ['next,text', 'next,text', 'next,text']