【问题标题】:Python print with multiple arguments vs printing an fstring带有多个参数的 Python 打印与打印 fstring
【发布时间】:2020-12-09 13:22:39
【问题描述】:

是否有一条潜规则,或者一条 PEP 规则表明在将某些内容打印到屏幕上时使用 f 字符串而不是使用带有多个参数的 print 更好? 示例:

age = 80
name = "John"
print(f'My name is {name} and I am {age} years old')
print('My name is', name, 'and I am', age, 'years old')

我试图向某人解释 f-string 更常用,但他一直坚持认为第二种选择更容易。这两个例子都可以,我只是好奇是否有规则建议使用 f 字符串,或者为什么将 print 与多个参数一起使用是不好的做法。

谢谢

【问题讨论】:

  • Python f-strings 仅存在于 3.6 之后,因此说它们被更多使用似乎不太现实。我在 PEP8 中没有找到任何关于打印的内容。但可以争论的是,使用多个参数进行打印对于 print 函数来说有点独特,当使用 f-strings 可以帮助在代码库中构建统一的字符串。
  • 我也喜欢第二种方法
  • 为什么你认为一个选项是首选?它们都有效,它们都具有相似的可读性。 f-strings 直到最近 (3.6+) 才存在,所以绝对没有历史支持它们。
  • 当我谈论更多使用时,我的意思是在较新的项目中。当我说它是首选时,我就这样做了,因为根据我的经验以及我与 f 字符串交互的人似乎是首选方式。

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


【解决方案1】:

在给出的示例中没有真正的区别。然而,在处理字符串时,您有时需要创建一个“参数”字符串:在这种情况下,您将不得不使用f-stringformat() 方法或old-style 字符串格式。如果主要取决于您的偏好和您的应用程序(例如,有时您被旧版本的 Python 阻止),则使用哪一个。

这些将起作用:

name = 'Johnny'
age = 18

# old-style
s1 = 'My name is %s and I am %s years old' % (name, age)

# format()
s2 = 'My name is {0} and I am {1} years old'.format(name, age)

# f-string
s3 = f'My name is {name} and I am {age} years old'

您可以将其视为 s1 --> s2 --> s3 的演变(所以更现代 - 更发达)

虽然这些不会按预期工作

# This will give a tuple
s4 = 'My name is', name, 'and I am', age, 'years old'

# This will throw an exception as the age is of the `int` type
s5 = 'My name is' + name + 'and I am' + age + 'years old'

我们还可以补充一点,一些nice features 可以通过字符串格式(s1、s2 和 s3)访问,而不能通过print(a, b, c) 访问。

【讨论】:

    【解决方案2】:

    我应该先说我个人更喜欢使用 f 字符串,因此我的回答可能偏向于使用它。 但是,我认为使用 f-strings 比使用多个参数至少有一个明显的优势,那就是 f-strings are strings

    这似乎是一个明显的观察,但这意味着我使用 f 字符串执行的任何操作操作也可以直接转换为 print() 之外的单个语句。然而,第二种方法使用了多个参数,这不是我可以打包成单独语句的东西。 IMO,这使得重构输出变得更加容易,因为您可以简单地将代码从打印语句复制并粘贴到其他地方并保持代码样式的一致性。

    另外一点是f弦的性能。虽然我没有看到与多参数 print()s 的明确比较,但有很多帖子将 f-strings 与其他方法进行比较(例如,这里 [https://realpython.com/python-f-strings/ #速度])。在我自己使用timeit 进行的快速实验中,我发现了以下内容:

    import timeit
    y = David
    x = Dan
    timeit.timeit("print(f'My name is {y} {x}')", setup="from __main__ import x,y", number=1000000)
    # 4.74 s
    
    timeit.timeit("print('My name is', y, x)", setup="from __main__ import x,y", number=1000000)
    # 5.72 s
    

    当然,打印语句的速度通常不是那么重要,但可能只是另一个论点。

    【讨论】:

      猜你喜欢
      • 2013-02-23
      • 2020-02-11
      • 1970-01-01
      • 1970-01-01
      • 2013-12-06
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      相关资源
      最近更新 更多