在 python SyntaxError: EOL 中扫描字符串文字 [英] In python SyntaxError: EOL while scanning string literal

查看:111
本文介绍了在 python SyntaxError: EOL 中扫描字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 python 3.5.1.当我尝试这个

I'm using python 3.5.1. When I was trying this

print(r'\t\\\')

我收到错误:语法错误:扫描字符串文字时EOL.但是这个效果很好

I got the error: SyntaxError: EOL while scanning string literal. But this one worked well

print(r'\t\\')

谁能解释一下?

推荐答案

首先,您要逃避关闭的 ',因此您在问题中提到的 SyntaxError 是引发,因为您的字符串现在永远不会终止.在第二个中,您要转义最后的 \,因此 ' 不会被转义.'\\' 是文字反斜杠而不是转义符,这就是为什么 ' 在第二个版本中没有转义,以及 '\' 在第一个版本的末尾没有转义.

In the first you are escaping your closing ', hence the SyntaxError you mention in your question is raised, because your string now never terminates. In the second you are escaping the final \ so the ' is not escaped. '\\' is a literal backslash rather than an escape, which is why the ' is not escaped in the second version, and why the '\' at the end of the first version is not escaped.

不知何故,我错过了您在谈论原始字符串.不过,请参阅 3.5 文档:

Somehow I missed that you were talking about raw strings. Still, see from the 3.5 docs:

即使在原始文字中,引号也可以用反斜杠转义,但是结果中保留反斜杠;例如,r"\"" 是一个有效的字符串文字由两个字符组成:一个反斜杠和一个双引号;r"\" 不是有效的字符串文字(即使是原始字符串也不能以奇数个反斜杠).具体来说,原始文字不能以单个反斜杠(因为反斜杠会转义以下内容引号字符).另请注意,单个反斜杠后跟换行符被解释为这两个字符作为文字的一部分,不是作为行的延续.

Even in a raw literal, quotes can be escaped with a backslash, but the backslash remains in the result; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw literal cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the literal, not as a line continuation.

这篇关于在 python SyntaxError: EOL 中扫描字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆