Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the difference between sep and end in print function?

pets = ['boa', 'cat', 'dog']
for pet in pets:
    print(pet)

boa
cat
dog
>>> for pet in pets:
        print(pet, end=', ')

boa, cat, dog, 
>>> for pet in pets:
        print(pet, end='!!! ')

boa!!! cat!!! dog!!! 

but what about sep? i tried to replace end by sep but nothing happened but i know that sep is used to separete while printing, how and when can i use sep? what are the differences between sep and end?

like image 479
MMM Avatar asked Apr 09 '16 05:04

MMM


2 Answers

The print function uses sep to separate the arguments, and end after the last argument. Your example was confusing because you only gave it one argument. This example might be clearer:

>>> print('boa', 'cat', 'dog', sep=', ', end='!!!\n')
boa, cat, dog!!!

Of course, sep and end only work in Python 3's print function. For Python 2, the following is equivalent.

>>> print ', '.join(['boa', 'cat', 'dog']) + '!!!'
boa, cat, dog!!!

You can also use a backported version of the print function in Python 2:

>>> from __future__ import print_function
>>> print('boa', 'cat', 'dog', sep=', ', end='!!!\n')
boa, cat, dog!!!
like image 142
Don Kirkby Avatar answered Oct 12 '22 07:10

Don Kirkby


The following two are equivalent:

print(*array, sep='abc')
print('abc'.join(str(x) for x in array))
like image 41
BallpointBen Avatar answered Oct 12 '22 07:10

BallpointBen