2

Is there a way to add comments into a multiline string, or is it not possible? I'm trying to write data into a csv file from a triple-quote string. I'm adding comments in the string to explain the data. I tried doing this, but Python just assumed that the comment was part of the string.

"""
1,1,2,3,5,8,13 # numbers to the Fibonnaci sequence
1,4,9,16,25,36,49 # numbers of the square number sequence
1,1,2,5,14,42,132,429 # numbers in the Catalan number sequence
"""

2 Answers 2

4

No, it's not possible to have comments in a string. How would python know that the hash sign # in your string is supposed to be a comment, and not just a hash sign? It makes a lot more sense to interpret the # character as part of the string than as a comment.


As a workaround, you can make use of automatic string literal concatenation:

(
"1,1,2,3,5,8,13\n" # numbers to the Fibonnaci sequence
"1,4,9,16,25,36,49\n" # numbers of the square number sequence
"1,1,2,5,14,42,132,429" # numbers in the Catalan number sequence
)
Sign up to request clarification or add additional context in comments.

Comments

0

If you add comments into the string, they become part of the string. If that weren't true, you'd never be able to use a # character in a string, which would be a pretty serious problem.

However, you can post-process the string to remove comments, as long as you know this particular string isn't going to have any other # characters.

For example:

s = """
1,1,2,3,5,8,13 # numbers to the Fibonnaci sequence
1,4,9,16,25,36,49 # numbers of the square number sequence
1,1,2,5,14,42,132,429 # numbers in the Catalan number sequence
"""
s = re.sub(r'#.*', '', s)

If you also want to remove trailing whitespace before the #, change the regex to r'\s*#.*'.

If you don't understand what these regexes are matching and how, see regex101 for a nice visualization.

If you plan to do this many times in the same program, you can even use a trick similar to the popular D = textwrap.dedent idiom:

C = functools.partial(re.sub, r'#.*', '')

And now:

s = C("""
1,1,2,3,5,8,13 # numbers to the Fibonnaci sequence
1,4,9,16,25,36,49 # numbers of the square number sequence
1,1,2,5,14,42,132,429 # numbers in the Catalan number sequence
""")

2 Comments

Hey, that works! What if you want to have a hash mark as part of the data, like: """!, @, #, $, %, ^, &, *, (, ) # symbols"""?
@HUAN5235 Then you have to come up with some unambiguous rule. If you never have hash marks as part of the comments, the rule could just be to match from the last hash mark, like re.sub(r'#[^#]*$', '', s, flags=re.MULTILINE). If both comments and text can have hash marks… you'll have to think something up, but whatever you come up with can probably be implemented.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.