用Python打印字符串格式的元组

2024-04-20 13:03:55 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我有这个问题。 我得到了元组(1,2,3),我应该用字符串格式打印它。 例如

tup = (1,2,3)
print "this is a tuple %something" % (tup)

这应该打印带括号的元组表示,比如

This is a tuple (1,2,3)

但是我得到的是TypeError: not all arguments converted during string formatting

我怎么能做到这一点?这里有点迷路了,如果你们能给我指个正确的方向:)


Tags: 字符串is格式notallthisargumentssomething
3条回答

上面给出的许多答案都是正确的。正确的方法是:

>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)

但是,对于'%'字符串运算符是否过时存在争议。正如许多人指出的那样,它绝对不是过时的,因为'%'字符串运算符更容易将字符串语句与列表数据组合在一起。

示例:

>>> 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,while.format()only support two conversion flags'!s''!r'

注意,%语法已经过时。使用str.format,它更简单,可读性更强:

t = 1,2,3
print 'This is a tuple {0}'.format(t)
>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)

使感兴趣的元组作为唯一项(即(thetuple,)部分)的单元组成为这里的关键位。

相关问题 更多 >