Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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='!!!
')
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='!!!
')
boa, cat, dog!!!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...