print "{0} ({1})"
在此代码中:
for x in [None,3,4.5,"foo",lambda : "moo",object,object()]:
print "{0} ({1})".format(x,type(x))
答案 0 :(得分:0)
正如评论中所提到的,它们是字符串的占位符,这里有一些例子的解释。还提到了文档here,它很好地解释了这一点。
当您为format
方法提供参数时,这些参数的值将在这些占位符中设置。参数的使用顺序取决于您如何编写这些占位符。实际上你甚至可以拥有空的占位符“{}”,它只是按顺序获取参数。
请注意以下示例。
假设设置了以下两个参数:
arg1 = "pretzels"
arg2 = "thirsty"
按顺序占位符:
print("These {0} are making me {1}".format(arg1, arg2))
输出:
These pretzels are making me thirsty
乱序占位符:
print("These {1} are making me {0}".format(arg1, arg2))
输出:
These thirsty are making me pretzels
占位符没有提供任何价值:
print("These {} are making me {}".format(arg1, arg2))
输出:
These pretzels are making me thirsty