在打印中正确使用 sep
Proper use of sep in print
我是 python 的新人,我在使用 sep= 时遇到问题。
我想要做的是在数字 25
和 .
之间没有 space
这是我的代码和我得到的错误。我是 运行 MAC OSX El Capitan 终端机上的此代码。
代码:
side = 5
area = side * side
print "The area of a square with side ",side,"is ",area,".",sep=" "
输出:
print "The area of a square with side ",side,"is ",area,".",sep=" "
^
SyntaxError: invalid syntax
sep
是 print()
function, which requires you use Python 3 or use a special from __future__ import print_function
statement in Python 2 (see the print()
function documentation 的参数。
普通的原版 Python 2 print
statement(您似乎正在使用)不支持更改使用的分隔符。
由于分隔符总是一个space,所以根本不需要在这里指定:
print "The area of a square with side ", side, "is ", area, "."
如果你想在没有 space 的情况下打印 ,请改用字符串格式:
print "The area of a square with side {} is {}.".format(side, area)
如果您使用 Python 3 教程使用 print(foo, bar, baz sep='')
或类似的语法,请自己安装 Python 3,或者获取 Python 2 特定教程相反。
在 python 2.x
中,print 不接受参数,因为 print 是一个语句 和 不是函数。
您可以通过从 future
模块导入来使用 print()
函数:
from __future__ import print_function
作为您的 .py
文件的第一次导入。
然后调用打印(不要省略括号!):
# This call is valid by default for Python 3.x
# It is also valid for Python 2 if you import the print_function
print ("The area of a square with side", side, "is", area, ".", sep=" ")
或者,Python 2
间距可以通过将它添加到要打印的字符串以及组合字符串的 +
运算符来显式添加:
# wrap int objects in str() to convert them to strings.
print "The area of a square with side " + str(side) + " is " + str(area) + "."
检查您的 python 版本(在您的终端中通过 运行 python -V
)并阅读正确的文档(Python 2, Python 3 )
我是 python 的新人,我在使用 sep= 时遇到问题。
我想要做的是在数字 25
和 .
这是我的代码和我得到的错误。我是 运行 MAC OSX El Capitan 终端机上的此代码。
代码:
side = 5
area = side * side
print "The area of a square with side ",side,"is ",area,".",sep=" "
输出:
print "The area of a square with side ",side,"is ",area,".",sep=" "
^
SyntaxError: invalid syntax
sep
是 print()
function, which requires you use Python 3 or use a special from __future__ import print_function
statement in Python 2 (see the print()
function documentation 的参数。
普通的原版 Python 2 print
statement(您似乎正在使用)不支持更改使用的分隔符。
由于分隔符总是一个space,所以根本不需要在这里指定:
print "The area of a square with side ", side, "is ", area, "."
如果你想在没有 space 的情况下打印 ,请改用字符串格式:
print "The area of a square with side {} is {}.".format(side, area)
如果您使用 Python 3 教程使用 print(foo, bar, baz sep='')
或类似的语法,请自己安装 Python 3,或者获取 Python 2 特定教程相反。
在 python 2.x
中,print 不接受参数,因为 print 是一个语句 和 不是函数。
您可以通过从 future
模块导入来使用 print()
函数:
from __future__ import print_function
作为您的 .py
文件的第一次导入。
然后调用打印(不要省略括号!):
# This call is valid by default for Python 3.x
# It is also valid for Python 2 if you import the print_function
print ("The area of a square with side", side, "is", area, ".", sep=" ")
或者,Python 2
间距可以通过将它添加到要打印的字符串以及组合字符串的 +
运算符来显式添加:
# wrap int objects in str() to convert them to strings.
print "The area of a square with side " + str(side) + " is " + str(area) + "."
检查您的 python 版本(在您的终端中通过 运行 python -V
)并阅读正确的文档(Python 2, Python 3 )