Python f-string:长字符串的缩进?
我在 Python 中面临长 f 字符串表达式的(审美)问题。例如,此代码片段
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}!'
给出以下错误,当然,这完全是预料之中的:
AssertionError: The provided value for x, namely 4, is invalid, the true value should be 3!
错误消息中有一个不需要的缩进,但在我看来,它看起来非常难看。避免这种情况的一种方法是编写
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}!'
# Do sth else.
然而,这对我来说也很难看,因为现在字符串的第二行与外部 '__main__'
函数具有相同的缩进。有没有办法让 AssertionError 正确显示,而无需将代码缩进为外部函数?
I'm facing (aesthetic) problems with long f-string expressions in Python. For example, this code snippet
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}!'
gives the following error, which is totally expected, of course:
AssertionError: The provided value for x, namely 4, is invalid, the true value should be 3!
There is an unwanted indentation in the error message that in my opinion looks very ugly, though. One way to circumvent this is to write
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}!'
# Do sth else.
However, this also looks ugly to me, as now the second line of the string has the same indentation as the outer '__main__'
function. Is there a way to have the AssertionError displayed properly without having to indent the code as the outer function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有2种情况可以解决你的问题。
示例:
例子:
There are 2 cases to solve your problem.
Example:
Example:
是的,利用隐式字符串连接,您可以这样做:
Yes, making use of implicit string concatenation, you can do this: