在Python中使用换行符的Sublime文本注释?

时间:2018-01-14 20:29:01

标签: python-2.7 comments sublimetext3

我注意到如果我在Sublime Text 3中使用注释分解了一长串Python,它会将前两个标记为红色(因此错误),尽管脚本运行良好。

# This is a long line broken up with comments 
"So I'm ready to attack, gonna lead the pack," + \ # red comment here
"Gonna get a touchdown, gonna take you out," + \ # and here
"That's right, put your pom-poms down, getting everybody fired up" # ok here

我是否必须使用正则表达式修复此问题,以我当前的语法风格修改Python的Sublime配置文件?

1 个答案:

答案 0 :(得分:1)

Python 2.7 Language reference可以在explicit line joining上说明这一点:

  

以反斜杠结尾的行无法发表评论。反斜杠不会继续发表评论。除了字符串文字之外,反斜杠不会继续使用令牌(即除了字符串文字之外的令牌不能使用反斜杠在物理行之间拆分)。反斜杠在字符串文字外的其他地方是非法的。

对于Python 2和Python 3,您发布的代码不被视为有效并产生错误:

  File "/home/tmartin/test.py", line 2
    x = "So I'm ready to attack, gonna lead the pack," +  # red comment here
                                                                           ^
SyntaxError: invalid syntax

Python Online Shell中执行此操作会提供更具体的错误消息:

Python 3.6.0 (default, Jan 13 2017, 00:00:00) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> "So I'm ready to attack, gonna lead the pack," + \ # red comment here
  File "<stdin>", line 1
    "So I'm ready to attack, gonna lead the pack," + \ # red comment here
                                                                        ^
SyntaxError: unexpected character after line continuation character

因此,Sublime在告诉您代码在这种情况下无效时似乎是正确的,如果没有Python解释器的修改版本,我无法看到任何方式让您的代码片段保持不变,尽管我是不是Python专家。

那就是说,假设这确实对你有用,那么阻止Sublime向你展示这些行是错误的唯一方法就是你手动编辑Sublime附带的Python语法,让它不要对待它情况无效。