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
Christopher Bottoms
  • 11,218
  • 8
  • 50
  • 99

3 Answers3

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',)
Grimmy
  • 3,992
  • 22
  • 25
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)
solarc
  • 5,638
  • 2
  • 40
  • 51
  • You need to enclose the string with ``()`` thought. This will yield a syntax error. – Grimmy Apr 28 '17 at 19:04
  • 1
    @Grimmy nice catch, only for the multiline one though, single line works just fine without parenthesis. – solarc Apr 28 '17 at 21:15
  • 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. – Grimmy Apr 28 '17 at 21:17
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)
Christopher Bottoms
  • 11,218
  • 8
  • 50
  • 99