使用格式运算符对变量本身的好处是什么?

时间:2017-12-09 22:01:35

标签: 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

name = str(input("Hello! What is your name? "))
age = int(input("How old are you?"))

output = name, "is", age, "years old."
print(output)

1 个答案:

答案 0 :(得分:1)

你不应该使用字符串插值

"%s is %d years old" % (name, age)        # old and busted

但应使用str.format

"{} is {:d} years old".format(name, age)  # modern

或Python 3.6 +中的f-strings

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!

或者您可能想要计算您想要的精确平均值,但只希望它显示为两位小数。

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}%"