Python SyntaxError:无效语法结束=''

2024-04-27 05:03:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习“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()

错误:

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

草图.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!

我花了两天时间想弄明白为什么代码不起作用。错误总是显示在“end=”中。


Tags: thenoyoudatalinethisargumentrole
3条回答

看起来您使用的是Python2.x,而不是Python3.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

在Python3.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>>>
>>> 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,

如果您是从命令行运行它,则可能只需要使用python3命令,而不只是python命令,例如:

python3 MyFile.py

相关问题 更多 >