Python长f-string表达式缩进问题及优化方案咨询
Great question—this is such a common frustration when you need to write a descriptive error message but don't want to sacrifice clean code indentation or end up with messy whitespace in the error output! Let's go through a few clean solutions that solve both problems.
Solution 1: Use Parentheses for String Concatenation (Best for Most Cases)
Python automatically concatenates string literals that are placed next to each other inside parentheses. This lets you split your f-string into multiple lines, keep proper indentation, and avoid any extra whitespace in the final error message:
if __name__ == '__main__': x_true = 3 x_prov = 4 assert x_prov == x_true, ( f'The provided value for x, namely {x_prov}, is invalid, ' f'the true value should be {x_true}!' )
When this assertion fails, you'll get a clean error message without any extra spaces:AssertionError: The provided value for x, namely 4, is invalid, the true value should be 3!
This approach works in all Python versions, keeps your code properly indented to match the surrounding function, and produces a seamless error message.
Solution 2: Use textwrap.dedent (For Multi-Line Error Messages)
If you want a multi-line error message (or just prefer writing the string as a single block), textwrap.dedent removes leading whitespace that's common to all lines, so you can indent the string naturally:
from textwrap import dedent if __name__ == '__main__': x_true = 3 x_prov = 4 error_msg = dedent(""" The provided value for x, namely {x_prov}, is invalid. The correct value should be {x_true}! """).strip() assert x_prov == x_true, error_msg.format(x_prov=x_prov, x_true=x_true)
Or if you're using Python 3.6+, you can combine it with an f-string (just make sure the dedent happens before the f-string is evaluated):
from textwrap import dedent if __name__ == '__main__': x_true = 3 x_prov = 4 error_msg = dedent(f""" The provided value for x, namely {x_prov}, is invalid. The correct value should be {x_true}! """).strip() assert x_prov == x_true, error_msg
Solution 3: Python 3.12+ Multi-Line F-Strings
If you're using Python 3.12 or newer, you can use the official multi-line f-string support, which lets you split the string across lines without needing concatenation or dedent:
if __name__ == '__main__': x_true = 3 x_prov = 4 assert x_prov == x_true, f""" The provided value for x, namely {x_prov}, is invalid, the true value should be {x_true}! """.strip()
The .strip() removes the leading and trailing newlines that come from the triple-quote syntax, giving you a clean single-line error message.
Final Recommendation
For most cases, Solution 1 (parentheses and string concatenation) is the best choice: it's compatible with all Python versions, keeps your code looking clean and properly indented, and produces a perfect error message without any extra work.
内容的提问来源于stack exchange,提问作者Imahn




