[英]Joining two multi lined strings
我正在尝试连接跨越多行的数据。 我不会告诉您这些数据来自何处,但不会弄得一团糟,但是它是以字符串的形式出现的,样本可能是这样的:
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
谢谢
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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.