在Python中的分隔线上打印列表元素

我试图打印出使用这个Pythonpath文件夹:

import sys print sys.path 

输出是这样的:

 >>> print sys.path ['.', '/usr/bin', '/home/student/Desktop', '/home/student/my_modules', '/usr/lib/pyth on2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/pyth on2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-pack ages', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/ usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/ python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/lib/p ython2.6/dist-packages/wx-2.8-gtk2-unicode'] 

如何将它们打印到单独的行中,以便我可以正确parsing它们?

应该是这样的:

 /usr/bin /home/student/Desktop /home/student/my_modules etc 
 print("\n".join(sys.path)) 

(为了Python 3的兼容性,外括号被包含在内,通常在Python 2中被省略)

 for path in sys.path: print path 

使用打印function(Python 3.x)或导入它(Python 2.6+):

 from __future__ import print_function print(*sys.path, sep='\n') 

处理这种选项的另一个很好的select是pprint模块,它(其中包括)可以打印每行只有一个元素的长列表:

 >>> import sys >>> import pprint >>> pprint.pprint(sys.path) ['', '/usr/lib/python27.zip', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/lib/python2.7/site-packages', '/usr/lib/python2.7/site-packages/PIL', '/usr/lib/python2.7/site-packages/gst-0.10', '/usr/lib/python2.7/site-packages/gtk-2.0', '/usr/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg-info', '/usr/lib/python2.7/site-packages/webkit-1.0'] >>> 

Sven Marnach的答案非常多,但有一个普遍性问题…如果打印的列表不只包含string,将会失败。

所以,“如何用换行符分隔元素打印列表”这个更一般的答案…

 print '\n'.join([ str(myelement) for myelement in mylist ]) 

再次,JBernardo指出的打印function方法是优越的。 如果可以的话,使用print函数而不是print语句几乎总是一个好主意。

尝试以下操作:

 import sys for row in sys.path: print(row)