【问题标题】:Fix this code with f-string for me?帮我用 f-string 修复这个代码?
【发布时间】:2017-04-04 15:51:25
【问题描述】:

当我阅读this

有这个代码

We can also do that this way:
We'd have 500000 beans, 500 jars, and 5 crates.

当我修改为 pep 498

print ("We can also do that this way:")
print (f"We'd have {secret_formula(start_point)} beans, {secret_formula(start_point)} jars, and {secret_formula(start_point)} crates.")

打印出来

We can also do that this way:
We'd have (500000, 500, 5) beans, (500000, 500, 5) jars, and (500000, 500, 5) crates.

【问题讨论】:

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


    【解决方案1】:

    我看到你正在关注LPTHW 教程,我strongly 建议你选择一个不同的教程,因为你目前的教程有一些非常有趣 的意见和some other issues

    回到您的问题:您需要将secret_formula() 调用解包为:

    b, j, c = secret_formula(start_point)
    
    print (f"We'd have {b} beans, {j} jars, and {c} crates.")
    

    f-strings 基本上只是将变量放在字符串中以调用它,并且由于 secret_formula() 返回一个元组,当您 fstring 只是调用该函数时,它将返回并打印该元组。

    【讨论】:

    • 你有什么关于 python 3 的书给我吗?
    • 如何用 f-string 打印这段代码? ``` print('{0:_^11}'.format('hello')) ```
    • @kunjun 和.format() 一样:print(f'{x:_^11}')
    【解决方案2】:

    我想把这段代码改成 f-string print "We can also do that this way:" print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2017-05-26
      • 1970-01-01
      • 2015-06-13
      • 2015-03-27
      相关资源
      最近更新 更多