Python中的换行注释是否可行?

时间:2010-02-24 08:08:52

标签: python comments

我有一个长字符串,我用一堆计算值构建。然后我将此字符串写入文件。 我的格式如下:

string = str(a/b)+\
         '\t'+str(c)\
         '\t'+str(d)\
         ...
         '\n' 

我想对每个值所代表的内容添加评论,但使用#'''进行评论不起作用。这是一个例子:

string = str(a/b)+\     #this value is something
         '\t'+str(c)\   #this value is another thing
         '\t'+str(d)\   #and this one too
         ...
         '\n'

我发现它不起作用:)所以我想知道在这样的情况下,带有干净语法的代码会是什么样的。

对我来说,唯一的选择就是在每一行都去string +=,但我正在摸索着“必须有更好的方法”。

2 个答案:

答案 0 :(得分:7)

一个简单的解决方案是使用括号:

string = (str(a/b)+      #this value is something
          '\t'+str(c)+   #this value is another thing
          '\t'+str(d)+   #and this one too
          ...
          '\n')

答案 1 :(得分:1)

怎么样

string = '\t'.join(map(str,((a/b),    #this value is something
                            c,        #this value is another thing
                            d,        #and this one too
                            )))+'\n'

或者如果您愿意

string = '\t'.join(map(str,(
        (a/b),    #this value is something
        c,        #this value is another thing
        d,        #and this one too
        )))+'\n'
相关问题