Printing list elements on separated lines in Python
我尝试使用以下方法打印出python路径文件夹:
1 2 | import sys print sys.path |
输出如下:
1 2 3 4 5 6 7 8 | >>> 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'] |
号
如何将它们打印成单独的行,以便正确地分析它们?
应该是这样的:
1 2 3 4 | /usr/bin /home/student/Desktop /home/student/my_modules etc |
1 2 | print(" ".join(sys.path)) |
(3 parentheses外都包含在Python Python中的兼容性和通常omitted 2。。。。。。。)
使用打印功能(Python 3.x)或它的(Python 2.6进出+):
1 2 3 4 | from __future__ import print_function print(*sys.path, sep=' ') |
1 2 | for path in sys.path: print path |
另一个很好的选择,这是一个什么样的处理模块是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | >>> 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'] >>> |
的答案是marnach斯文很漂亮,但是有一个问题generality……它将失败,如果列表中包含的字符串是不是只是印制。
更多的操作系统,一般的回答"如何打印出与由换行符分隔的列表元素的"……
1 2 | print ' '.join([ str(myelement) for myelement in mylist ]) |
然后再次,打印功能的方法是jbernardo点"上。如果你可以使用打印功能,可以打印的报表几乎永远是很好的想法。
尝试以下:
1 2 3 | import sys for row in sys.path: print(row) |