【问题标题】:Why is the following string literal allowed?为什么允许以下字符串文字?
【发布时间】:2014-03-31 17:56:18
【问题描述】:

在处理某些问题时生成不同的字符串组合, 观察以下行为

In [3]: str = 'abcd'

In [4]: str
Out[4]: 'abcd'

In [5]: str = 'ab'cd'
------------------------------------------------------------
   File "<ipython console>", line 1
     str = 'ab'cd'
              ^
SyntaxError: invalid syntax


In [6]: str = 'ab''cd'

In [7]: str
Out[7]: 'abcd'

我知道单引号字符串可以在其间包含双引号,而双引号字符串可以在其间包含单引号。

有人可以解释一下,为什么我们会观察到这种行为,在单引号字符串中允许同时使用两个单引号,但不允许单引号。

【问题讨论】:

    标签: python string python-2.7 python-3.x


    【解决方案1】:

    Python 隐式连接附近的字符串,它们之间没有任何内容。观察:

    >>> 'hel'  'lo'
    'hello'
    >>> 'cat'        'egory'
    'category'
    >>> 'ab''cd'
    'abcd'
    

    单引号为奇数的字符串是不明确的,因此是不允许的。

    >>> 'ab'cd'   # Here `cd` is a bareword and ' starts an unterminated string
      File "<stdin>", line 1
        'ab'cd'
             ^
    SyntaxError: invalid syntax
    >>> 'ab\'cd'  # The middle single quote is escaped so this is OK
    "ab'cd"
    

    如果您忘记了逗号,在处理列表时这可能是一种“陷阱”:

    >>> ['a', 'b', 'c' 'd', 'e']  # no comma between 'c' and 'd'
    ['a', 'b', 'cd', 'e']
    

    【讨论】:

    • +1。附带说明:各种语言都显示出这种行为。在 python 中,你甚至可以混合使用不同的字符串分隔符:'aa' "bb" '''cc''' 解析得很好。
    猜你喜欢
    • 2011-01-31
    • 1970-01-01
    • 2011-03-05
    • 2021-07-18
    • 2012-03-07
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多