6

Is the following syntax not supported by f-strings in Python 3.6? If I line join my f-string, the substitution does not occur:

SUB_MSG = "This is the original message."

MAIN_MSG = f"This longer message is intended to contain " \
             "the sub-message here: {SUB_MSG}"

print(MAIN_MSG)

returns:

This longer message is intended to contain the sub-message here: {SUB_MSG}

If I remove the line-join:

SUB_MSG = "This is the original message."

MAIN_MSG = f"This longer message is intended to contain the sub-message here: {SUB_MSG}"

print(MAIN_MSG)

it works as expected:

This longer message is intended to contain the sub-message here: This is the original message.

In PEP 498, backslashes within an f-string are expressly not supported:

Escape sequences

Backslashes may not appear inside the expression portions of f-strings, so you cannot use them, for example, to escape quotes inside f-strings:

>>> f'{\'quoted string\'}'

Are line-joins considered 'inside the expression portion of f-strings' and are thus not supported?

MSeifert
  • 145,886
  • 38
  • 333
  • 352
JS.
  • 14,781
  • 13
  • 63
  • 75
  • 1
    Not supported within the *expression portions of f-strings*, not elsewhere. Also, just add `f` to the second string literal. This is consistent with how other string prefixes work: `len(r"\\" "\\") == 3`. – Ry- Oct 24 '17 at 22:10

2 Answers2

7

You have to mark both strings as f-strings to make it work, otherwise the second one is interpreted as normal string:

SUB_MSG = "This is the original message."

MAIN_MSG = f"test " \
           f"{SUB_MSG}"

print(MAIN_MSG)

Well, in this case you could also just make the second string the f-string because the first one doesn't contain anything to interpolate:

MAIN_MSG = "test " \
           f"{SUB_MSG}"

Note that this affects all string-prefixes not just f-strings:

a = r"\n" \
     "\n"
a   # '\\n\n'   <- only the first one was interpreted as raw string

a = b"\n" \
     "\n"   
# SyntaxError: cannot mix bytes and nonbytes literals
MSeifert
  • 145,886
  • 38
  • 333
  • 352
3

Try this (note the extra “f” on the continuation line):

SUB_MSG = "This is the original message."

# f strings must be aligned to comply with PEP and pass linting
MAIN_MSG = f"This longer message is intended to contain " \
           f"the sub-message here: {SUB_MSG}"


print(MAIN_MSG)
eatsfood
  • 950
  • 2
  • 21
  • 31
Lawrence D'Oliveiro
  • 2,768
  • 1
  • 15
  • 13