Or b
Or b

Reputation: 816

Is there a difference between backslash and triple quotes?

I understand that on string assignment that exceeds 1 line you can use either backslash, parenthesis or triple quotes. Is there any practical difference? Which is considered a better coding practice?

For example:

STR1 = """Peanut
        butter
        jam"""

STR2 = "Peanut" \
       "butter" \
       "jam"

STR3 = ("Peanut"
        "butter"
        "jam")

All of which run perfectly fine, but which one is less prone to future bugs, or is a better practice?

Upvotes: 0

Views: 647

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122032

STR1 is, as pointed out in snatchysquid's answer, actually a different string to STR2 and STR3. This may not be relevant, depending on the case (e.g. when using regular expressions you can turn on the verbose flag to ignore the extra whitespace).

Between STR2 and STR3, the guidance in PEP8 suggests the latter:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

With the backslashes, you also can't have comments:

>>> STR2 = "Peanut" \
...        "butter" \  # optional
  File "<stdin>", line 2
    "butter" \  # optional
                         ^
SyntaxError: unexpected character after line continuation character
>>> STR3 = ("Peanut"
...         "butter"  # optional
...         "jam")
>>> 

Upvotes: 1

snatchysquid
snatchysquid

Reputation: 1352

There is a difference indeed since using triple quotes doesn't discount the line feed, \n, when pressing Enter while the others don't include them, only what's inside the quotes is used.

look at this simple code printing each of them:

STR1 = """Peanut
        butter
        jam"""

STR2 = "Peanut" \
       "butter" \
       "jam"

STR3 = ("Peanut"
        "butter"
        "jam")


print(STR1)
print(STR2)
print(STR3)

Here's the result:

Peanut
        butter
        jam
Peanutbutterjam
Peanutbutterjam

Upvotes: 0

Related Questions