Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is line wrap comment possible in Python?

I have a long string that I build with a bunch of calculated values. I then write this string to a file. I have it formatted like:

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

I would like to add comment to what each value represents but commenting with # or ''' doesn't work. Here's an example:

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

I figured out it doesn't work :) so I'm wondering what code with a clean syntax would look like in a situation like this.

The only option that occurs to me would be to go for string += on each line but I'm scratching my head with "there must be a better way".

like image 359
greye Avatar asked Feb 24 '10 08:02

greye


People also ask

Can you comment out lines in Python?

To comment out multiple lines in Python, you can prepend each line with a hash ( # ). With this approach, you're technically making multiple single-line comments. The real workaround for making multi-line comments in Python is by using docstrings.

How do you line wrap in Python?

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

How do you enclose comments in Python?

A comment in Python starts with the hash character, # , and extends to the end of the physical line. A hash character within a string value is not seen as a comment, though.

What is inline comment in Python example?

Python inline commentsWhen you place a comment on the same line as a statement, you'll have an inline comment. Similar to a block comment, an inline comment begins with a single hash sign ( # ) and is followed by a space and a text string.


2 Answers

A simple solution is to use parenthesis instead:

string = (str(a/b)+      #this value is something
          '\t'+str(c)+   #this value is another thing
          '\t'+str(d)+   #and this one too
          ...
          '\n')
like image 200
sth Avatar answered Oct 19 '22 22:10

sth


How about

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

Or if you prefer

string = '\t'.join(map(str,(
        (a/b),    #this value is something
        c,        #this value is another thing
        d,        #and this one too
        )))+'\n'
like image 45
John La Rooy Avatar answered Oct 19 '22 23:10

John La Rooy