我正在尝试打印两个列表,但它只打印列表中每个项目的第一个字母;
lst1 = ['hello', 'hi', 'sup']
lst2 = ['bye', 'cya', 'goodbye']
for item in [lst1, lst2]:
print 'Your options are: ' + ' '.join(['-{0}'.format(*x) for x in item])
结果;
You can choose: -h -h -s
You can choose: -b -c -g
如何完整打印字符串?
答案 0 :(得分:4)
从*
删除format
对您有用:
>>> for item in [lst1, lst2]:
... print 'Your options are: ' + ' '.join(['-{0}'.format(x) for x in item])
...
Your options are: -hello -hi -sup
Your options are: -bye -cya -goodbye
解释:*my_list
解压缩列表。由于,字符串也是list
的{{1}},chars
将变为:'-{0}'.format(*x)
。因此,它只是将字符串插入'-{0}'.format(['h', 'e', 'l', 'l', 'o'])
的第0个索引,即['h', 'e', 'l', 'l', 'o']
。
答案 1 :(得分:0)
替代;
>>> print '\n'.join('Your options are: -%s' % ' -'.join(x) for x in (lst1, lst2))
Your options are: -hello -hi -sup
Your options are: -bye -cya -goodbye
生成一行输出:
>>> 'Your options are: -%s' % ' -'.join(lst1)
'Your options are: -hello -hi -sup'
要生成完整的输出,上述内容适用于lst1
和lst2
,并与'\n'.join(...)
结合使用。