【发布时间】:2021-08-23 19:43:30
【问题描述】:
【问题讨论】:
-
好奇你在学习字符串格式化之前了解了
pickle -
%s是如此 python 2 。 . .试试f-strings
【问题讨论】:
pickle
%s 是如此 python 2 。 . .试试f-strings
% 表示传入字符串的参数。%s 是应视为字符串的参数
那里还使用了一些其他类型的参数类型,例如 %d 用于十进制整数,%f 用于浮点数等。
【讨论】:
%s 是使用 python 中旧格式化方法的字符串占位符。在您的示例中,基本上%s 被my_int 的字符串值替换。以下是@Paul Cornelius 提供的一些文档:https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting。
如果您想在自己的代码中更好地工作,有一些更新的方法可以做到这一点,pickle 可能会使用旧样式,因为它们没有真正的升级理由。
在 python 3.6+ 中,您可以通过在字符串声明前面放置一个 f 并使用 {variable_name} 来访问一个值来使用 fstrings。就像在这个例子中:
name = "John Smith" # A dummy name
email_count = 3 # A representation of users # of new emails
current_temperature = 20.3567 # A representation of the current temperature in celsius
greeting = f"Hello, {name} The weather today is {current_temperature} degrees. You have {email_count} new emails."
print(greeting)
这会导致打印
Hello John Smith The weather today is 20.3567 degrees. You have 3 new emails.
这相当于使用 % 方法来做:
name = "John Smith" # A dummy name
email_count = 3 # A representation of users # of new emails
current_temperature = 20.3567 # A representation of the current temperature in celsius
greeting = "Hello, %s The weather today is %03.2f degrees. You have %d new emails." % (name, current_temperature, email_count)
print(greeting)
其中%s 替换为字符串,%03.2f 替换为四舍五入到最接近的2 位小数的浮点数,%d 替换为整数。此方法被替换的主要原因之一是因为 F 字符串更易于阅读,并且不需要您提前知道放入其中的所有内容的类型(只需使用对象的 __repr__()),而例如 %d 将仅适用于整数,或者可以调用 int(obj) 的对象。
【讨论】: