0

I want to create a string, but include comments for each part. In Python, I can do this inside the function print, but I can't do it if I'm creating a variable.

print("Hello "  + # WORKS
       "World!")

greeting = "Hello " + # FAILS
           "World!"

print(greeting)

Throws the error:

  File "space.py", line 4
    greeting = "Hello " + # FAILS
                                ^
SyntaxError: invalid syntax

I tried line continuation:

greeting = "Hello " + \# FAILS
           "World!"

print(greeting)
  File "line_continuation.py", line 4
    greeting = "Hello " + \# FAILS
                                 ^
SyntaxError: unexpected character after line continuation character
2

3 Answers 3

2

If you want to have control over spaces you can simply do:

print("This "  # comment 1
      "is "  # comment 2
      "a "  # comment 3
      "test")  # comment 4

s = ("This "  # comment 1
     "is "  # comment 2
     "a "  # comment 3
     "test")  # comment 4
print(s)

Outputs:

This is a test
This is a test

Using comma will add a space between each string and is specific to print. The method shown above works for strings in general anywhere.

Note that this will represent a single string, so if you want to inject variables you need to .format on the last line.

The practice of using () around strings are often confused with making a tuple, but it's not a tuple unless it contains a comma.

s = ("Hello")
print(type(s), s)
s = ("Hello",)
print(type(s), s)

Outputs:

<class 'str'> Hello
<class 'tuple'> ('Hello',)
Sign up to request clarification or add additional context in comments.

Comments

2

You can break a string into multiple lines by simply putting them one after the other:

a = ("hello " # can use comments
    "world")
print(a)

b = "hello " "world" # this also works
print(b)

c = a " again" # but this doesn't, SyntaxError
print(c)

3 Comments

You need to enclose the string with () thought. This will yield a syntax error.
@Grimmy nice catch, only for the multiline one though, single line works just fine without parenthesis.
yeah it took me maybe two years before I picked up that ("hello") is a string and ("hello",) is a tuple. Even added it to my answer. So easy to mess that up.
0

I just figured it out. Adding parentheses around the parts of the string being constructed works:

print("Hello "  + # WORKS
       "World!")

greeting =("Hello " + # WORKS TOO
           "World!")

print(greeting)

2 Comments

By "commas" do you mean "parentheses"?
@BrenBarn Thanks! I totally know the difference. Don't know why I wrote "commas".

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.