简体   繁体   English

当字符串周围的引号不匹配时,为什么 Python 不会给出任何错误?

[英]Why doesn't Python give any error when quotes around a string do not match?

I've started learning Python recently and I don't understand why Python behaves like this:我最近开始学习 Python,我不明白为什么 Python 会这样:

>>> "OK"
'OK'
>>> """OK"""
'OK'
>>> "not Ok'
  File "<stdin>", line 1
    "not Ok'
           ^
SyntaxError: EOL while scanning string literal
>>> "not OK"""
'not OK'

Why doesn't it give an error for the last statement as the number of quotes does not match?由于引号的数量不匹配,为什么最后一条语句不会出错?

The final """ is not recognized as a triple-quotation, but a single " (to close the current string literal) followed by an empty string "" ;最后的"""不被识别为三重引号,而是单个" (以关闭当前字符串文字) 后跟一个空字符串"" the two juxtaposed string literals are concatenated.两个并列的字符串文字被连接起来。 The same behavior can be more readily recognized by putting a space between the closing and opening " .通过在关闭和打开之间放置一个空格,可以更容易地识别相同的行为"

>>> "not OK" ""
'not OK'

"not OK"""

Python interprets this as "not OK"+"" Python 将其解释为"not OK"+""

If you give "not Ok""ay" , you will get the output as 'not Okay'如果你给"not Ok""ay" ,你会得到输出为'not Okay'

You would think that there is no difference between " or ', but in reality, Python uses a greedy method to accept input.你会认为 " 或 ' 之间没有区别,但实际上,Python 使用贪婪的方法来接受输入。

Once Python sees a matching quotation, then that ends the statement.一旦 Python 看到匹配的引用,语句就结束了。

It's why you can write something like "'s" "" .这就是为什么你可以写类似"'s" "" Inside the string there is a ' but because you're in a string, python doesn't raise an error.在字符串中有一个'但因为你在一个字符串中,python 不会引发错误。 Then after that, there is a " followed by " but that's a different (empty) string.然后在那之后,有一个"后跟"但这是一个不同的(空)字符串。

If you do something like "s' then Python is looking for that next " before if runs your command.如果您执行类似"s'那么 Python 会在 if 运行您的命令之前寻找下一个"

Python uses like a stack implementation to detect quotes opening and closing. Python 使用堆栈实现来检测引号的打开和关闭。 If you know whats a stack is, its a datastructure, in which Last element will be removed first.如果您知道堆栈是什么,那么它是一个数据结构,其中最后一个元素将首先被删除。

Assume your string is A = "''" What it does is, for every single quote or double quote encountered first time, it will add it the stack, and for every second, it will remove from the stack, unless its ofcourse, """ which will be parsed as single one假设你的字符串是A = "''"它的作用是,对于第一次遇到的每一个单引号或双引号,它都会将它添加到堆栈中,并且每一秒,它都会从堆栈中移除,除非它当然, """将被解析为单个

In our example, A = "''" , iterating over it, for the first 2 elements, they will be added to stack and for the next 2, they will be removed.在我们的示例中, A = "''"迭代,对于前 2 个元素,它们将被添加到堆栈中,对于接下来的 2 个元素,它们将被删除。

So the quotes will be matched, if and only if, the number of elements in the stack in the end must be zero所以引号将被匹配,当且仅当,堆栈中的元素数量最终必须为零

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

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