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".
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.
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.
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.
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.
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')
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With