VPfB
VPfB

Reputation: 17332

How are f-strings handled in implicit string concatenation?

I made this mistake:

key, value = 'K', 999
msg = (
    f"key={key}, "
    "value={value}"  # needs to be prefixed with f as well
    )
# key=K, value={value}

and started wondering how Python handles complex cases of literal concatenation.

Let's assume one string is f-string (formatted string literal) and the other a plain string literal as in the example above. Does Python concatenate such two strings at compile time? And if yes what is the result?

Upvotes: 10

Views: 16103

Answers (1)

ely
ely

Reputation: 77464

From PEP 498:

Adjacent f-strings and regular strings are concatenated. Regular strings are concatenated at compile time, and f-strings are concatenated at run time.

Each f-string is entirely evaluated before being concatenated to adjacent f-strings.

Upvotes: 8

Related Questions