【问题标题】:How to make python printf return this? [closed]如何让 python printf 返回这个? [关闭]
【发布时间】:2019-09-10 18:26:39
【问题描述】:

我需要print(f"" + xx) 来输出text aaa,但它输出{x} 我怎样才能做到这一点?

我已尝试使用 printf 和 .format,但无法使其中任何一个工作

x = "aa"
xx = "text {x}"
x = "aaa"
print(f"" + xx)

【问题讨论】:

标签: python python-3.x formatting printf string.format


【解决方案1】:

您需要将要打印的变量放入f"{}"

x = "aa"
xx = "{x}"
x = "aaa"
print(f"{x}")

否则,xx 字面意思是"{x}" 并且不会扩展。

【讨论】:

    【解决方案2】:

    我想你想使用str.format,而不是 f-string。

    xx = "text {x}"
    x = "aaa"
    print(xx.format(x=x))  # -> text aaa
    

    或者不显式传递x

    print(xx.format(**locals()))  # -> text aaa
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 2017-09-27
      • 1970-01-01
      相关资源
      最近更新 更多