简体   繁体   English

为什么 Try 块在 Python3 中执行 except 块之前重新调整 SyntaxError?

[英]why Try block is retuning SyntaxError before executing except block in Python3?

Here I am trying to print "Invalid text" when the string contains Backslash " \ ".在这里,当字符串包含反斜杠“\”时,我试图打印“无效文本”。 I know that in Python strings, the backslash " \ " is a special character called the "escape" character.我知道在 Python 字符串中,反斜杠“\”是一个特殊字符,称为“转义”字符。 But when python tries to read the variable s, it returns SyntaxError.但是当 python 尝试读取变量 s 时,它会返回 SyntaxError。

try:
     s = '\'
except:
    print("Invalid text")

output is output 是

File "C:\Users\Admin\PycharmProjects\pythonProject19\main.py", line 4
    raise SyntaxError if s = '\':
                              ^
SyntaxError: unterminated string literal (detected at line 4)

Because of \ , your code should be as the following.由于\ ,您的代码应如下所示。

try:
     s == '\\'
except:
    print("Invalid text")

Read more about Python Escape Characters here: https://www.w3schools.com/python/gloss_python_escape_characters.asp在此处阅读有关Python 转义字符的更多信息: https://www.w3schools.com/python/gloss_python_escape_characters.asp

You have an unterminated string literal.The proper way to terminate a string literal as is described by you in this instance is s == '\\' .您有一个未终止的字符串文字。在这种情况下,您所描述的终止字符串文字的正确方法是s == '\\'

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

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