带有多个参数的 Python 打印与打印 fstring

标签 python python-3.x f-string

是否有潜规则或 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/

相关文章:

python - 如何推迟/推迟 f 弦的评估?

python - 在 OR 工具中通过 SWIG 使用 Python 回调

python - set_column 未将颜色格式应用于大型 Excel 文件的列

python - 语法无效 - 表达式返回 f-String 中的字符串

python - 输出是一列数字而不是一个总数

python - 如何在 Python 3.2 或更高版本中使用 'hex' 编码?

python - 字符串格式 : % vs. .format 与 f-string 文字

python - 是否可以使用 Python 和 cx_Oracle 进行空间查询?

python - 使用 .bat 更改目录并运行 Jupyter

python - 我的第一个程序