用Python中的string格式打印元组
所以,我有这个问题。 我得到了元组(1,2,3),我应该用string格式打印。 例如。
tup = (1,2,3) print "this is a tuple %something" % (tup) 这应该使用括号来打印元组表示
这是一个元组(1,2,3)
 但是我得到TypeError: not all arguments converted during string formatting 。 
我怎么能做到这一点? 有点在这里输了,所以如果你们可以指点我一个正确的方向:)
 >>> thetuple = (1, 2, 3) >>> print "this is a tuple: %s" % (thetuple,) this is a tuple: (1, 2, 3) 
 使用感兴趣的元组作为唯一的(thetuple,)即(thetuple,)部分,是这里的关键。 
 请注意, %语法已过时。 使用str.format ,它更简单,更易读: 
 t = 1,2,3 print 'This is a tuple {0}'.format(t) 
 >>> tup = (1, 2, 3) >>> print "Here it is: %s" % (tup,) Here it is: (1, 2, 3) >>> 
 注意(tup,)是包含元组的元组。 外部元组是%运算符的参数。 内部元组是它的内容,实际上是打印的。 
  (tup)是括号内的expression式,当评估结果为tup 。 
  (tup,) ,后面的逗号是一个元组,它包含tup作为唯一的成员。 
这不使用string格式,但你应该能够做到:
 print 'this is a tuple ', (1, 2, 3) 
如果你真的想使用string格式:
 print 'this is a tuple %s' % str((1, 2, 3)) # or print 'this is a tuple %s' % ((1, 2, 3),) 
请注意,这假定您使用的是早于3.0的Python版本。
上面给出的许多答案是正确的。 正确的做法是:
 >>> thetuple = (1, 2, 3) >>> print "this is a tuple: %s" % (thetuple,) this is a tuple: (1, 2, 3) 
 但是,对'%'string运算符是否过时存在争议。 正如很多人指出的那样,它绝对不是过时的,因为'%'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 
 此外, '%'string运算符对于validation数据types(例如%s , %d , %i )也很有用,而.format() 只支持两个转换标志 : '!s'和'!r' 。 
 t = (1, 2, 3) # the comma (,) concatenates the strings and adds a space print "this is a tuple", (t) # format is the most flexible way to do string formatting print "this is a tuple {0}".format(t) # classic string formatting # I use it only when working with older Python versions print "this is a tuple %s" % repr(t) print "this is a tuple %s" % str(t) 
我认为最好的办法是:
 t = (1,2,3) print "This is a tuple: %s" % str(t) 
如果您熟悉printf样式格式,那么Python支持自己的版本。 在Python中,这是通过使用应用于string的“%”运算符(模运算符的重载)完成的,该运算符接受任何string并对其应用printf样式格式。
在我们的例子中,我们告诉它打印“这是一个元组:”,然后添加一个string“%s”,对于实际的string,我们传入一个string表示的元组(通过调用str T))。
如果你不熟悉printf风格的格式,我强烈build议学习,因为它是非常标准的。 大多数语言都以这种或那种方式支持它。
请注意,如果元组只有一个项目,将会添加尾随逗号。 例如:
 t = (1,) print 'this is a tuple {}'.format(t) 
你会得到:
 'this is a tuple (1,)' 
在某些情况下,例如你想得到一个引用的列表,在MySQL查询string中使用
 SELECT name FROM students WHERE name IN ('Tom', 'Jerry'); 
在格式化之后,你需要考虑删除尾部逗号use replace(',)',')',因为这个元组可能只有1个项目('Tom',),所以需要删除拖尾的逗号:
 query_string = 'SELECT name FROM students WHERE name IN {}'.format(t).replace(',)', ')') 
请build议,如果你有体面的方式在输出中删除这个逗号。
说话很便宜,给你看代码:
 >>> tup = (10, 20, 30) >>> i = 50 >>> print '%d %s'%(i,tup) 50 (10, 20, 30) >>> print '%s'%(tup,) (10, 20, 30) >>>