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

新手上路,请多包涵
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 替换 end 但什么也没发生,但我知道 sep 在打印时用于分隔,我如何以及何时可以使用 sep? sep 和 end 有什么区别?

原文由 MMM 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 607
2 个回答

打印函数 使用 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 中使用向后移植版本的打印函数:

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

原文由 Don Kirkby 发布,翻译遵循 CC BY-SA 3.0 许可协议

下面两个是等价的:

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

原文由 BallpointBen 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题