Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing list elements on separate lines in Python

Tags:

python

I am trying to print out Python path folders using this:

import sys print sys.path 

The output is like this:

>>> 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'] 

How do I print them into separate lines so I can parse them properly?

It should be like this:

/usr/bin /home/student/Desktop /home/student/my_modules etc 
like image 722
Larry Avatar asked May 29 '11 12:05

Larry


People also ask

How do you print a list of elements on a different line in Python?

Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.

How do you print a list individually in Python?

When you wish to print the list elements in a single line with the spaces in between, you can make use of the "*" operator for the same. Using this operator, you can print all the elements of the list in a new separate line with spaces in between every element using sep attribute such as sep=”/n” or sep=”,”.

How do you print multiple items on one line Python?

To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")


2 Answers

print("\n".join(sys.path)) 

(The outer parentheses are included for Python 3 compatibility and are usually omitted in Python 2.)

like image 158
Sven Marnach Avatar answered Oct 03 '22 09:10

Sven Marnach


Use the print function (Python 3.x) or import it (Python 2.6+):

from __future__ import print_function  print(*sys.path, sep='\n') 
like image 31
JBernardo Avatar answered Oct 03 '22 09:10

JBernardo