Python 什么';在变量本身上使用格式运算符的好处是什么?
相当简单的问题-在什么情况下,您更喜欢使用格式运算符而不是变量本身?它们只是为了代码可读性,还是有其他合法用途Python 什么';在变量本身上使用格式运算符的好处是什么?,python,python-3.x,string-formatting,Python,Python 3.x,String Formatting,相当简单的问题-在什么情况下,您更喜欢使用格式运算符而不是变量本身?它们只是为了代码可读性,还是有其他合法用途 name = str(input("Hello! What is your name? ")) age = int(input("How old are you?")) output = "%s is %d years old." % (name, age) print(output) VS 不应该使用字符串插值 "%s is %d years old" % (name, age)
name = str(input("Hello! What is your name? "))
age = int(input("How old are you?"))
output = "%s is %d years old." % (name, age)
print(output)
VS
不应该使用字符串插值
"%s is %d years old" % (name, age) # old and busted
但应改为使用str.format
"{} is {:d} years old".format(name, age) # modern
或Python 3.6中的f字符串+
f"{name} is {age} years old" # new hotness
你的例子不是等价的,但是即使它们只是展示字符串格式化的最基本的特征——把变量放在字符串的中间。相反,让我们看看更多的中间特性,如填充:
headers = ["some", "words", "that", "are", "headers", "to", "a", "table"]
让我们想象一下,我们想要大小相等的列,因此我们不能只执行以下操作:
' '.join(headers) # "some words that are headers to a table"
# ^--- not equal-size columns!
但必须格式化每个字符串
common_width = max(map(len, headers))
result = ' '.join(["{h:<{width}}".format(h=h, width=common_width) for h in headers])
# "some words that are headers to a table"
# ^--- equal-size columns!
common_width=max(贴图(长度、标题))
结果=“”。连接([”{h:格式运算符对浮点数、在开头或左/右填充中添加零非常有用。您的两个示例完全不同。output
在您的第二个示例中是一个元组,在第一个示例中是一个字符串。您是否确实检查了输出?无论如何,老式的%
格式非常不受欢迎,您应该使用python 3.6中的.format
甚至f-strings。您的第二个示例是元组,而不是字符串,您的输出将有很大的不同。您可以使用打印(*输出)获得相同的结果
也许吧,但是字符串格式可以做的远不止是将值转换为字符串。例如,尝试添加列宽,然后对齐。或者对数字进行零填充。然后使对齐或列宽变量。然后混合需要支持不同格式操作的自定义类型。字符串格式(特别是使用str.format()
)比只在一行中输出几个值要强大得多。在str.format()
示例中,如果要使其等效于printf样式模板,至少使用:d
格式说明符。
common_width = max(map(len, headers))
result = ' '.join(["{h:<{width}}".format(h=h, width=common_width) for h in headers])
# "some words that are headers to a table"
# ^--- equal-size columns!
data = [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
sum_ = sum(data)
length = len(data)
avg = sum_ / length * 100
print("Average is " + str(avg) + "%")
# "Average is 63.63636363636363%"
print("Average is {:.02f}%".format(avg))
# "Average is 63.64%" <-- clearly easier to read!
# equivalently: f"Average is {avg:.02f}%"