20

How to add comments to multiline assignments in python, as is possible in C with the syntax:

char sc[] = "\x31\xdb"                  /* xor %ebx, %ebx       */
            "\x31\xc9"                  /* xor %ecx, %ecx       */
            "\xb8\x46\x00\x00\x00"      /* mov $0x46, %eax      */
            "\xcd\x80"                  /* int $0x80            */
            "\x31\xdb"                  /* xor %ebx, %ebx       */
            "\xb8\x01\x00\x00\x00"      /* mov $0x1, %eax       */
            "\xcd\x80";                 /* int $0x80            */

but the same in python, using escaped line breaks

sc = "\x31\xdb" \   # xor %ebx, %ebx
     "\x31\xc9" \   # xor %ecx, %ecx
     "…"
2
  • I don't get what the question/problem is. The latter syntax looks as valid Python comment syntax. It's the line continuation that's wrong. Commented Feb 8, 2013 at 19:12
  • 4
    It is a real question. I understand what he is asking. He is asking for a way to put a comment in the middle of a (continued) line. As can be done with a block comment in C/C++. There is no such feature in python, so the only solution (and it is a good one) is to bracket the code with parentheses, as in the accepted answer. NOTE: Triple quotes can sort-of be used as block comments in python, but only on a separate line: if do """is this a comment?""" at end of line (before backslash), it will be treated as a string in the code. In this code, would be appended to the desired string. Commented Dec 8, 2013 at 0:56

1 Answer 1

30

You can write

sc = ("\x31\xdb"      # xor %ebx, %ebx
      "\x31\xc9"      # xor %ecx, %ecx
      "…")

if you want.

Sign up to request clarification or add additional context in comments.

5 Comments

+1, Using brackets to get implied line continuation is the best option here.
@Lattyware Or anywhere really. Backslash line continuations are Weird And Fiddly (tm).
(And you lose editor highlighting that tells you where the line really ends.)
the reason it does not work as on the question is because the \ escapes the line break. but if you put a space to add a comment, now the \ escapes the space. which does nothing. the solution here keeps the list open until the ) is seen, which can happen on several lines. on python, the start of a comment is threated as a (unescapable) line break. in fact, the C code only works because it is expecting the ; as well.
In fact it is a heck?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.