是否有潜规则或 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 弦更常用,但他一直坚持认为第二种选择更容易。这两个示例都可以使用,我只是好奇是否有建议使用 f 字符串的规则,或者为什么将 print 与多个参数一起使用是不好的做法。
谢谢
最佳答案
在给出的示例中没有真正的区别。然而,在处理字符串时,您有时需要创建一个“参数化”字符串:在这种情况下,您将不得不使用 f-string
。 , format()
方法或 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'
You can see it as an evolution s1 --> s2 --> s3 (so more modern - more developed)
虽然这些不会按预期工作
# 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)
访问。
关于带有多个参数的 Python 打印与打印 fstring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65217674/