简体   繁体   English

将结束参数与打印函数一起使用时的 Python SyntaxError

[英]Python SyntaxError when using end argument with print function

I don't know why i get the error because i have done exactly as the book says我不知道为什么会出现错误,因为我完全按照书上的说明做了

>>> os.getcwd()
'C:\\Users\\expoperialed\\Desktop\\Pyt…'
>>> data = open('sketch.txt')
>>> print(data.readline(),end="")
SyntaxError: invalid syntax

Or, to use the print function like you want in Python 2:或者,在 Python 2 中使用您想要的打印函数:

>>> from __future__ import print_function

That will need to be at the top of your Python program though because of the way the __future__ module works.由于__future__模块的工作方式,这需要位于 Python 程序的顶部。

I think your problem is that you are on Python 2.x and are using Python 3.x's syntax.我认为您的问题是您使用的是 Python 2.x 并且使用的是 Python 3.x 的语法。 In Python 3.x, print is a built-in and can be used like that.在 Python 3.x 中, print是内置的,可以这样使用。 However, in 2.x, it is a keyword and cannot.但是,在 2.x 中,它是关键字,不能。 If you are on 2.x, do this:如果您使用的是 2.x,请执行以下操作:

print data.readline(),

One way to see which version of Python you are using is this:查看您使用的 Python 版本的一种方法是:

import sys
if sys.version_info.major == 2:
    # We are running 2.x
elif sys.version_info.major == 3:
    # We are running 3.x

or, from the terminal:或者,从终端:

$ python --version

The best way to fix this problem would probably be to upgrade to Python 3.x.解决此问题的最佳方法可能是升级到 Python 3.x。 However, if you can't, then you might want to look at the __future__ module.但是,如果您不能,那么您可能需要查看__future__模块。 It can make it so that you can use Python 3.x's print function in 2.x:它可以使您可以在 2.x 中使用 Python 3.x 的print功能:

>>> from __future__ import print_function
>>> print("yes!")
yes!
>>> print("a", "b", sep=",")
a,b
>>>

It looks like you're running the wrong python version.看起来您运行的是错误的 Python 版本。 There's currently 2 versions of Python running around, 2 and 3. In Python 2, print is a statement so you should change your code too目前有 2 个版本的 Python 正在运行,2 和 3。在 Python 2 中, print是一个语句,因此您也应该更改代码

 print data.readline(), # The trailing comma to stop the newline

while in 3 it's a function and should be used how your book shows.而在 3 中,它是一个函数,应该用于您的书的显示方式。

It looks like your book is in Python 3 so you should upgrade your python (For a beginner there's no reason not to use Python 3)看起来你的书是 Python 3,所以你应该升级你的 Python(对于初学者来说,没有理由不使用 Python 3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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