formatter = "%r %r %r %r"
#formatter = "%s %s %s %s"
print(formatter % (1, 2, 3, 4) )
print(formatter % ("one", "two", "three", "four"))
print(formatter % (True, False, False, True) )
print(formatter % (formatter, formatter, formatter, formatter))
print( formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight."
)
)
面对这个程序,大量的%让我感到头疼,我并不清楚%r与%s的区别与使用方法。在经过一定的查找后我找到了最合适的解释:
这是Python中的字符串格式化。
在这个例子中,%r
是一个占位符,用于表示将要被替换的值。
在第一个print语句中,%r
被替换为1、2、3和4。在第二个print语句中,%r
被替换为字符串"one"、“two”、“three"和"four”。
在第三个print语句中,%r
被替换为True、False、False和True。
在第四个print语句中,%r
被替换为formatter本身四次。
在最后一个print语句中,formatter被替换为"I had this thing.", “That you could type up right.”, “But it didn’t sing.”, and “So I said goodnight.”。
请注意,这里使用的是%r占位符,而不是%s占位符。%r占位符用于调试目的,因为它会显示原始数据,而不是字符串的解释版本。如果使用%s占位符,则会显示字符串的解释版本。