【问题标题】:Syntax error on opening quotation mark左引号的语法错误
【发布时间】:2015-03-07 08:14:55
【问题描述】:

我正在尝试运行 Think Python 一书中练习 3.3 的脚本:

问题:Python 提供了一个名为 len 的内置函数,它返回字符串的长度,因此 len('allen') 的值是 5。编写一个名为 right_justify 的函数,它接受一个名为 s 的字符串作为参数,并打印带有足够前导空格的字符串,以便字符串的最后一个字母在显示的第 70 列中。

到目前为止,我已经解决了一些脚本问题,现在我有了这个:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def right_justify(s):
    print ‘ ‘ * (70 - len(s)) + s

right_justify(‘allen’)

当我尝试运行它时,我收到以下错误:

 File "/Users/Jon/Documents/Python/Chapter 3/right justify.py", line 5
    print ‘ ‘ * (70 - len(s)) + s
          ^
SyntaxError: invalid syntax

我犯了什么错误,我应该怎么做才能修复这个脚本?

【问题讨论】:

  • 应该是:print ' ' * (70 - len(s)) + s
  • 您可能需要考虑切换文本编辑器。如果您使用像TextEdit 这样不是为代码设计的编辑器,您很可能会遇到类似这样的有趣问题。我个人推荐Sublime,但还有很多其他优秀的编辑。

标签: python syntax-error quotes quote quotation-marks


【解决方案1】:

解析器无法识别 字符。您需要对字符串文字使用撇号或引号('"):

print ' ' * (70 - len(s)) + s

有关详细信息,请参阅文档中的Strings literals

【讨论】:

    【解决方案2】:

    你正在使用的角色

    print ‘ ‘ * (70 - len(s)) + s
    

    是一个非 ascii 撇号,虽然您可以在代码中使用 unicode 文字,但不能将它们用于单引号。您需要 ascii 单引号,',(有时也用作撇号),

    print ' ' * (70 - len(s)) + s
    

    或双引号:

    print " " * (70 - len(s)) + s
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-15
      • 2021-12-02
      • 1970-01-01
      相关资源
      最近更新 更多