打印功能中sep和end之间有什么区别?

时间:2016-04-09 05:15:40

标签: python python-2.7 python-3.x

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

但是sep怎么样?我试图用sep替换end但是什么都没发生但我知道sep在打印时用于separete,我如何以及何时可以使用sep? sep和end之间有什么区别?

3 个答案:

答案 0 :(得分:8)

print function使用sep分隔参数,并在最后一个参数后使用end。你的例子令人困惑,因为你只给了它一个参数。这个例子可能更清楚:

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

当然,sepend仅适用于Python 3的打印功能。对于Python 2,以下内容是等效的。

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

您还可以在Python 2中使用backported版本的print函数:

>>> from __future__ import print_function
>>> print('boa', 'cat', 'dog', sep=', ', end='!!!\n')
boa, cat, dog!!!

答案 1 :(得分:0)

月=''并结束=''是两回事。忽略空格并将变量作为单个字符串..例如:end='' - > ab 但a b使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 ''' - > a b 见下面的例子。 对于sep =' '

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

for end =' '

{{1}}

答案 2 :(得分:0)

在数组变量而不是sep中,您可以使用join

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

输出

boa,cat,dog
相关问题