gpt4 book ai didi

python - 为 Python 2 解压打印列表

转载 作者:太空狗 更新时间:2023-10-29 22:15:05 24 4
gpt4 key购买 nike

我无法理解为什么解包不适用于 Python 2.7 中的列表和打印语句:

>>> l=['a', 'b', 'c']
>>> print (*l, sep='')

Python 3.x 工作正常并打印:

abc

然而,Python 2.7 会引发错误:

 print (*l, sep='')
^
SyntaxError: invalid syntax

如何让它适用于 Python 2.7?

我知道我也可以使用 join with 对其进行编码:''.join(l)

最佳答案

因为 print 不是 Python 2 中的函数;如果列表不是函数,则无法解压缩列表并将其作为位置参数提供

您需要从 __future__ 导入 print_function 以支持此功能:

>>> from __future__ import print_function

现在可以解包了:

>>> l = ['a', 'b', 'c']
>>> print(*l, sep='')
abc

关于python - 为 Python 2 解压打印列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41047108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com