【问题标题】:How do I handle errors in an f-string?如何处理 f 字符串中的错误?
【发布时间】:2020-06-26 13:20:40
【问题描述】:

我正在尝试处理 f 字符串中的错误,但我的尝试似乎不起作用。有没有办法做到这一点?

string = f"For example I thought this syntax would work but it doesn't {try: 5/0 except Exception: str(infinity)}"

【问题讨论】:

标签: python python-3.x error-handling f-string


【解决方案1】:

你不能。将异常处理移出 f-string。

【讨论】:

  • 从你的观点来看,我猜你是最后的仲裁者。悲伤,但公平。
  • 你如何建议我把它从 f-string 中取出来?
【解决方案2】:

您可以尝试在编写 fstring 之前处理您需要的任何内容并将其存储为变量,然后您可以在 fstring 中引用该变量,如下所示:

from math import inf

try:
    div_by_zero = 5/0
except ZeroDivisionError:
    div_by_zero = str(inf)

my_string = f"Processed outside: {div_by_zero}"

【讨论】:

  • 一个好的答案将始终包括解释为什么这会解决问题,以便 OP 和任何未来的读者可以从中学习。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 2015-01-21
  • 1970-01-01
  • 2011-08-11
  • 2017-08-06
  • 2015-05-24
  • 1970-01-01
相关资源
最近更新 更多