Python SyntaxError:语法无效end =''

Jon*_*nny 19 python python-3.x

我正在研究"Head First Python"这本书,我遇到了这段代码的麻烦:

data = open('sketch.txt')

for each_line in data:
    (role, line_spoken) = each_line.split(':')
    print(role, end='')
    print(' said: ', end='')
    print(line_spoken, end='')

data.close()
Run Code Online (Sandbox Code Playgroud)

错误:

  File "Aula 3.py", line 12
      print(role, end='')
               ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

sketch.txt:

Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't!
Other Man: Yes I have.
Man: When?
Other Man: Just now.
Man: No you didn't!
Other Man: Yes I did!
Man: You didn't!
Other Man: I'm telling you, I did!
Man: You did not!
Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?
Man: Ah! (taking out his wallet and paying) Just the five minutes.
Other Man: Just the five minutes. Thank you.
Other Man: Anyway, I did.
Man: You most certainly did not!
Other Man: Now let's get one thing quite clear: I most definitely told you!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh look, this isn't an argument!
(pause)
Other Man: Yes it is!
Man: No it isn't!
Run Code Online (Sandbox Code Playgroud)

我有两天时间试图找出代码无效的原因.该错误始终显示在"end =''"中.

fal*_*tru 27

看起来你正在使用Python 2.x,而不是Python 3.x.

检查你的python版本:

>>> import sys
>>> sys.version
'2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)]'
>>> print(1, end='')
  File "<stdin>", line 1
    print(1, end='')
                ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

在Python 3.x中,它不应该引发语法错误:

>>> import sys
>>> sys.version
'3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)]'
>>> print(1, end='')
1>>>
Run Code Online (Sandbox Code Playgroud)

  • @Venkatesh,通过在代码的第一行添加以下行,您可以使用`print`作为Python 3.x之类的函数:`from __future__ import print_function` (9认同)
  • @falsetru有没有解决Python 2.x的问题? (2认同)

小智 6

>>> import sys
>>> print(sys.version)
2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)]
>>> from __future__ import print_function
>>> print(1, end=',')
1,
Run Code Online (Sandbox Code Playgroud)