控制台中出现 Python 错误,但文件 : unexpected character after line continuation character 中没有

标签 python console

我有一个 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/

相关文章:

Python - 在字符串中查找日期

windows - 在 Windows 控制台中设置 Mercurial 以完成命令

python - Scrapy 登录表单

python - Pygame - 为什么 LSHIFT 在按键重复模式下不响应

python - 用\and 分隔的十六进制数据是什么类型的?

python - 如果它们之间的差异小于 pandas 中的固定值,则将行值替换为先前的值

php - Symfony 控制台 ContainerAwareCommand $this->getContainer() 产生 fatal error

google-chrome - Protractor - 不要在导航后清除控制台日志

java - 打印钻石 - 无法输入?

android - Eclipse 控制台不显示日志