上面给出的许多答案都是正确的。正确的做法是:
>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)
但是,对于 '%' 字符串运算符是否已过时存在争议。正如许多人所指出的,它绝对不会过时,因为'%' String 运算符更容易将 String 语句与列表数据结合起来。
例子:
>>> tup = (1,2,3)
>>> print "First: %d, Second: %d, Third: %d" % tup
First: 1, Second: 2, Third: 3
但是,使用.format() 函数,您会得到一个冗长的语句。
例子:
>>> tup = (1,2,3)
>>> print "First: %d, Second: %d, Third: %d" % tup
>>> print 'First: {}, Second: {}, Third: {}'.format(1,2,3)
>>> print 'First: {0[0]}, Second: {0[1]}, Third: {0[2]}'.format(tup)
First: 1, Second: 2, Third: 3
First: 1, Second: 2, Third: 3
First: 1, Second: 2, Third: 3
此外,'%' 字符串运算符对我们验证数据类型也很有用,例如%s、%d、%i,而 .format() only support two conversion flags: '!s' 和 '!r' .