【问题标题】:For multiline string value, can you add comment on the first line? [duplicate]对于多行字符串值,您可以在第一行添加注释吗? [复制]
【发布时间】:2020-10-15 04:20:57
【问题描述】:

对于多行字符串值如下:

var_a = "This is a very very"\
"very long string that "\
"consists of 3 lines"

只能在最后一行添加注释。示例:

var_a = "This is a very very"\
"very long string that "\
"consists of 3 lines" #add comment here

在其他任何地方添加注释是语法错误。

有什么方法可以在第一行添加注释吗?

【问题讨论】:

  • 在你的字符串周围加上括号并去掉反斜杠。然后你可以在每一行的末尾添加注释。

标签: python-3.x


【解决方案1】:

简短的回答是否定的! '/' 之后的所有内容都将生成 Syntax Error。 没有办法绕过它,但你可以做的就是对变量上方的每一行注释 3 次。

# This is line 1 comment
# This is line 2 comment
# This is line 3 comment 
var_a = "This is a very very"\
"very long string that "\
"consists of 3 lines"

注释对于程序员来说是一项非常重要的实践,最佳实践是在代码行上方进行注释。

【讨论】:

    【解决方案2】:

    我建议使用括号而不是反斜杠将语句拆分为多行。这将允许您将 cmets 放在每一行上,并且不易出错。

    var_a = ("This is a very very " # comment 1
             "very long string that " # comment 2
             "consists of 3 lines") # comment 3
    

    【讨论】:

      猜你喜欢
      • 2021-08-17
      • 2017-04-28
      • 2021-12-13
      • 2016-11-04
      • 2018-10-31
      • 2023-03-28
      • 2018-02-04
      • 2011-05-07
      • 1970-01-01
      相关资源
      最近更新 更多