我有一个 Python 脚本,其中有一个使用此方法定义的类:
@staticmethod
def _sanitized_test_name(orig_name):
return re.sub(r'[`‘’\"]*', '', re.sub(r'[\r\n\/\:\?\<\>\|\*\%]*', '', orig_name.encode('utf-8')))
我可以从命令提示符运行该脚本,没有任何问题。但是,当我将完整类的代码粘贴到控制台中时,我收到 SyntaxError: unexpected character after line continuation character
:
>>> return re.sub(r'[`‘’\"]*', '', re.sub(r'[\r\n\/\:\?\<\>\|\*\%]*', '', orig_name.encode('utf-8')))
File "<stdin>", line 1
return re.sub(r'[``'\"]*', '', re.sub(r'[\r\n\/\:\?\<\>\|\*\%]*', '', orig_name.encode('utf-8')))
^
SyntaxError: unexpected character after line continuation character
如果我在粘贴时跳过该方法,它就会起作用。请注意,我的原始行和错误显示的内容有所不同: r'[`''\"]*'
与 r'[``'"]* '
。将其替换为 ur'[`''"]*'
会产生 SyntaxError: EOL while Scanning string Literal
。
Python 控制台似乎将 '
视为风格化的 `
(反引号),将 '
视为风格化的 '
(单引号)。当我真正的意思是 unicode open and close quotes 。我的脚本顶部有 # -*-coding: utf-8 -*-
,我也将其粘贴到控制台中。
最佳答案
仅关注导致错误的表达式r'[`''"]*'
...
>>> r'[`‘’"]*'
File "<stdin>", line 1
r'[``'"]*'
^
SyntaxError: EOL while scanning string literal
>>> ur'[`‘’"]*' # with the unicode modifier
File "<stdin>", line 1
ur'[``'"]*'
^
SyntaxError: EOL while scanning string literal
如果我所在的终端不接受 unicode 输入,则 unicode 字符从 '
到 `
和 '
的解释到'
,发生。
因此解决方法是拆分正则表达式并使用 unichr()
以及 2018 年和 2019 年两个报价的相应代码:
>>> r'[`' + unichr(2018) + unichr(2019) + r'"]*'
u'[`\u07e2\u07e3"]*'
(这个特定的正则表达式可能不需要原始字符串修饰符 r''
。)
关于控制台中出现 Python 错误,但文件 : unexpected character after line continuation character 中没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39372362/