Python中f-string与普通字符串隐式拼接的编译时处理问询
Great question—this is exactly the kind of subtle Python behavior that catches even seasoned programmers off guard. Let’s break this down step by step.
先解释你的示例结果
First, let’s unpack why your code produces key=K, value={value} instead of the expected key=K, value=999:
key, value = 'K', 999 msg = ( f"key={key}, " "value={value}" # 同样需要加f前缀 )
The issue here is that only the first string is an f-string—the second one is a regular string literal. Python doesn’t retroactively apply f-string formatting to adjacent regular strings. The f-string gets evaluated at runtime (replacing {key} with 'K'), then it’s concatenated with the unmodified regular string value={value}. That’s why you end up with the literal {value} in the final result.
核心问题:编译时是否会拼接这类字符串?
Now to your main question: Does Python concatenate f-strings and regular string literals at compile time? The short answer is no—this concatenation happens at runtime, but let’s clarify the details:
- For regular string literals (non-f-strings) placed next to each other (like
"a" "b"), Python does perform concatenation at compile time. The bytecode will load a single combined string instead of two separate ones. - However, f-strings are evaluated at runtime because they can contain dynamic expressions (like variables or function calls). When you pair an f-string with a regular string literal, Python compiles this into code that first evaluates the f-string to its final string value, then performs a runtime concatenation with the regular string.
You can verify this with the dis module, which shows the bytecode Python generates. Take this simplified example:
import dis def concat_example(): x = 999 return f"x={x}" "y=hello" dis.dis(concat_example)
The bytecode output will show steps to:
- Load the value of
x - Evaluate the f-string to produce
"x=999" - Load the regular string literal
"y=hello" - Perform a binary addition (string concatenation) at runtime
- Return the combined result
拼接结果是什么?
As seen in your example, the final concatenated string is:
[evaluated f-string value] + [original regular string literal]
So if your f-string resolves to "key=K, " and the regular string is "value={value}", the result is "key=K, value={value}". To get the expected formatted value for value, you need to mark the second string as an f-string too:
msg = ( f"key={key}, " f"value={value}" ) # Result: "key=K, value=999"
Alternatively, you could combine them into a single f-string, which is often cleaner:
msg = f"key={key}, value={value}"
内容的提问来源于stack exchange,提问作者VPfB

