Christopher Bottoms
Christopher Bottoms

Reputation: 11158

How can I break string creation over several lines, but include inline comments

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

Upvotes: 0

Views: 62

Answers (3)

solarc
solarc

Reputation: 5738

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)

Upvotes: 2

Grimmy
Grimmy

Reputation: 4137

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',)

Upvotes: 2

Christopher Bottoms
Christopher Bottoms

Reputation: 11158

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)

Upvotes: 0

Related Questions