我想要一个包含三个列表数据的单个字符串
喜欢
list_1 = ['Modified', 'Modified', 'Added', 'Added']
list_2 = ['92', '92', '92', '92']
list_3 = ['trunk/new','trunk', 'branch','oldpath']
我的字符串应该是:
"Modified/92 trunk/new
Modified/92 trunk
Added/92 branch
Added/92 oldpath"
如何添加这些列表得到这种字符串?
答案 0 :(得分:3)
您可以在此处使用str.join
,zip
和一些string formatting:
>>> s = '\n'.join('{0}/{1} {2}'.format(*x) for x in zip(list_1, list_2, list_3))
>>> print s
Modified/92 trunk/new
Modified/92 trunk
Added/92 branch
Added/92 oldpath
使用itertools.starmap
的另一种选择:
>>> from itertools import starmap, izip
>>> f = '{0}/{1} {2}'.format
>>> print '\n'.join(starmap(f, izip(list_1, list_2, list_3)))
Modified/92 trunk/new
Modified/92 trunk
Added/92 branch
Added/92 oldpath
如果您只需要字符串打印目的,那么不要创建字符串,只需使用print()
函数:
>>> from __future__ import print_function #Required in Python 2
>>> print(*starmap(f, izip(list_1, list_2, list_3)), sep='\n')
Modified/92 trunk/new
Modified/92 trunk
Added/92 branch
Added/92 oldpath
答案 1 :(得分:1)
你可以这样做:
list_1 = ['Modified', 'Modified', 'Added', 'Added']
list_2 = ['92', '92', '92', '92']
list_3 = ['trunk/new','trunk', 'branch','oldpath']
s = ' '.join(a+'/'+b+' '+c for a,b,c in zip(list_1, list_2, list_3)) #for separation with spaces
或者
s = '\n'.join(a+'/'+b+' '+c for a,b,c in zip(list_1, list_2, list_3)) #for new lines
[OUTPUT]
Modified/92 trunk/new Modified/92 trunk Added/92 branch Added/92 oldpath