Search code examples
pythonstringpython-3.xpython-3.6f-string

Is line-joining unsupported by f-strings?


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?


Solution

  • 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