37

I'm new to python and have a simple array:

op = ['Hello', 'Good Morning', 'Good Evening', 'Good Night', 'Bye']

When i use pprint, i get this output:

['Hello', 'Good Morning', 'Good Evening', 'Good Night', 'Bye']

Is there anyway i can remove the quotes, commas and brackets and print on a seperate line. So that the output is like this:

Hello
Good Morning
Good Evening
Good Night
Bye
Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118

5 Answers5

50

You could join the strings with a newline, and print the resulting string:

print "\n".join(op)
Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118
43

For Python 3, we can also use list unpack
https://docs.python.org/3.7/tutorial/controlflow.html#unpacking-argument-lists

print(*op, sep='\n')

It's the same as

print('Hello', 'Good Morning', 'Good Evening', 'Good Night', 'Bye', sep='\n')
Ryan Chu
  • 1,381
  • 13
  • 20
11

Here's a couple points of clarification

  1. First of all what you have there is a list, not an array. The difference is that the list is a far more dynamic and flexible data structure (at list in dynamic languages such as python). For instance you can have multiple objects of different types (e.g have 2 strings, 3 ints, one socket, etc)

  2. The quotes around the words in the list denote that they are objects of type string.

  3. When you do a print op (or print(op) for that matter in python 3+) you are essentially asking python to show you a printable representation of that specific list object and its contents. Hence the quotes, commas, brackets, etc.

  4. In python you have a very easy for each loop, usable to iterate through the contents of iterable objects, such as a list. Just do this:

    for greeting in op: 
         print greeting
    
KyleMit
  • 30,350
  • 66
  • 462
  • 664
NlightNFotis
  • 9,559
  • 5
  • 43
  • 66
6

Print it line by line

for word in op:
    print word

This has the advantage that if op happens to be massively long, then you don't have to create a new temporary string purely for printing purposes.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
1

You can also get some nicer print behavior by using the Pretty Print library pprint

Pretty print will automatically wrap printed contents when you go over a certain threshold, so if you only have a few short items, it'll display inline:

from pprint import pprint
xs = ['Hello', 'Morning', 'Evening']
pprint(xs)
# ['Hello', 'Morning', 'Evening']

But if you have a lot of content, it'll auto-wrap:

from pprint import pprint
xs = ['Hello', 'Good Morning', 'Good Evening', 'Good Night', 'Bye', 'Aloha', 'So Long']
pprint(xs)
# ['Hello',
#  'Good Morning',
#  'Good Evening',
#  'Good Night',
#  'Bye',
#  'Aloha',
#  'So Long']

You can also specify the column width with the width= param.

See Also: How to print a list in Python "nicely"

KyleMit
  • 30,350
  • 66
  • 462
  • 664