加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

为什么在Python 3中,四重引号会产生语法错误?

发布时间:2020-12-20 12:13:50 所属栏目:Python 来源:网络整理
导读:我可以在三引号字符串的开头添加其他引号,但不能添加到结尾.这是为什么?这段代码: print(""""String that starts with quadruple quotes and ends with triple quotes""") 生成此输出: "String that starts with quadruple quotes and ends with triple q
我可以在三引号字符串的开头添加其他引号,但不能添加到结尾.这是为什么?这段代码:

print(""""
String that starts with quadruple quotes and ends with triple quotes
""")

生成此输出:

"
String that starts with quadruple quotes and ends with triple quotes

但是这个代码块不起作用:

print(""""
String that starts with quadruple quotes and ends with quadruple quotes
"""")

它会产生以下错误:

File "example.py",line 3
    """")
        ^
SyntaxError: EOL while scanning string literal

我不需要使用四重引用字符串,但我很好奇为什么Python不会让我这样做.谁能帮我理解?

解决方法

你不能在三引号字符串的值中的任何地方使用“”“.不是在开头,而是在结尾.

这是因为,在前三个“”“开头字符表示这样一个字符串的开头之后,另一个”“”序列总是将成为字符串的结尾.您的第四个“位于您创建的字符串对象之外,而单个”没有关闭“不是有效的字符串.

Python没有其他方法可以知道这样的字符串何时结束.你不能随意在最终的“”之前“添加”字符“向内”扩展字符串,因为这与有效和合法的*无法区分:

>>> """string 1"""" string 2"
'string 1 string 2'

如果你必须包括“在结束之前”“”,请逃避它.您可以在前面加上反斜杠来执行此操作:

>>> """This is triple-quoted string that
... ends in a single double quote: """"
'This is triple-quoted string thatnends in a single double quote: "'

请注意,不存在四重引用字符串. Python不允许你将“引号”任意组合成更长的序列.只存在“单引号”和“”“三引号”“”语法(使用“或”).三引号字符串的规则与单引号字符串不同;前者允许换行,而后者不允许换行.

有关更多详细信息,请参阅参考文档的String and Bytes literals section,其中将语法定义为:

06002

并明确提到:

In triple-quoted literals,unescaped newlines and quotes are allowed (and are retained),except that three unescaped quotes in a row terminate the literal. (A “quote” is the character used to open the literal,i.e. either ' or ".)

(大胆强调我的).

*表达式是合法的,因为它包含两个字符串文字,一个带有“”引用,下一个带有“引用”.连续字符串文字会自动连接,就像它们在C中一样.见String literal concatenation.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读