简体   繁体   中英

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?

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!!!

The following two are equivalent:

print(*array, sep='abc')
print('abc'.join(str(x) for x in array))

sep='' and end='' are two different thing. ignore space and make variable as a single string.. like: ab -->ab But end='' make ab -->ab see the below example. for sep=' '

from itertools import permutations
s,k = input().split()
for i in list(permutations(sorted(s), int(k))):
    print(*i,sep='')

    ''' output for sep='': 
    HACK 2
    AC
    AH
    AK
    CA
    CH
    CK
    HA
    HC
    HK
    KA
    KC
    KH
    '''

for end=' '

    from itertools import permutations

    s, k = input().split()
    for i in list(permutations(sorted(s), int(k))):
        print(*i, end='')
    '''
HACK 2
A CA HA KC AC HC KH AH CH KK AK CK H
Process finished with exit code 0
'''

In array variable instead of sep you can use join

pets = ['boa', 'cat', 'dog']
res=",".join(pets)
print(res)

Output

boa,cat,dog

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM