Simkill
Simkill

Reputation: 345

Unexpected print behaviour Python 3

I'm running through a tutorial for python 3 and I'm getting strange behaviour on printing. for example:

print ("\nUnpickling lists.")
pickle_file = open("pickles1.dat", "rb")
variety = pickle.load(pickle_file)
shape = pickle.load(pickle_file)
brand = pickle.load(pickle_file)
print (variety,"\n",shape,"\n",brand)
pickle_file.close()

gives me:

Unpickling lists.
['sweet', 'hot', 'dill'] 
 ['whole', 'spear', 'chip'] 
 ['Claussen', 'Heinz', 'Vlassic']

How do I avoid the extra space at the beginning of the lines of print output for the second and third lists?

Upvotes: 0

Views: 110

Answers (2)

mata
mata

Reputation: 69082

Just specify '\n' as separator, that will spare you to add a newline beteween every item:

print(variety, shape, brand, sep='\n')

Upvotes: 7

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251136

Use sep = '':

print (variety,"\n",shape,"\n",brand, sep = '')

Default value of sep is a single space:

>>> print('a','b')
a b
>>> print('a','b', sep ='')
ab

help on print: print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file:  a file-like object (stream); defaults to the current sys.stdout.
sep:   string inserted between values, default a space.          <-----
end:   string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

Upvotes: 3

Related Questions