在Python中使用字符串格式打印元组


126

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

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

这应该打印带有括号的元组表示形式,例如

这是一个元组(1,2,3)

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

我到底该怎么做?Kinda在这里输了,所以如果你们能指出我正确的方向:)

Answers:


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

用感兴趣的元组作为唯一项(即(thetuple,)零件)制作单例元组是这里的关键。


在Python 3中,print是一个函数,而不是一个语句,因此您必须编写print(....)
JG

53

请注意,该%语法已过时。使用str.format,它更简单易读:

t = 1,2,3
print 'This is a tuple {0}'.format(t)

我为这个1元组的情况在此stackoverflow.com/a/26249755/1676424中添加了评论
Jacob CUI 2014年

我不知道为什么%过时了,但str.format无论如何我现在总是盲目地对待你。没关系,我对完全限定词是什么感兴趣,因为简单{0}的不是完全限定词,而只是位置指示符。对于int,我称之为完全限定符{0:d}(或{3:d}例如,如果要打印的int出现在方法的第4个位置str.format)。我尝试使用{0:s}限定符打印一个元组,但是它不起作用。那么,像元组这样的完全限定词是什么?

1
@Ray真的没有道理。您可以指定很多选项,这些选项可以在文档中找到。如果要使用打印内容str,可以说{!s},但这是默认设置,因此没有必要。如果您想repr改用,则可以这样做{!r}。与with不同的是%,不需要说d整数。

2
我有点喜欢%s语法,因为它在我的脑海中不如新格式那么冗长,并且也非常类似于我知道并喜欢的c字符串格式
Paulus

请注意,即使在Python 3上,%也不是完全过时的。实际上,pylint如果您.formatlogging模块中使用以下语法,甚至会抱怨: stackoverflow.com/a/34634301/534238
Mike Williamson,

39

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

>>> 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

进一步,'%'串操作者也为我们验证数据类型如有用%s%d%i,而.format()只支持两个转换标志'!s''!r'


我过渡到使用format(),但是%方法的这种优势(能够格式化元组的每个元素并进行转换)很大,所以我想我会回头。谢谢。
比尔

1
您也可以为每个元素指定格式。'{:d} {:s}'。format(1,'2')
zk82

5
在“星号解包”元组效果很好.formattup = (1,2,3); print('First: {}, Second: {}, Third: {}'.format(*tup))
m-dz

25
>>> tup = (1, 2, 3)
>>> print "Here it is: %s" % (tup,)
Here it is: (1, 2, 3)
>>>

请注意,这(tup,)是一个包含元组的元组。外部元组是%运算符的参数。内部元组是其内容,它实际上是打印的。

(tup)是括号中的表达式,计算时结果为tup

(tup,)后跟逗号的是一个元组,它tup仅包含一个成员。


9

这不使用字符串格式,但是您应该能够:

print 'this is a tuple ', (1, 2, 3)

如果您确实要使用字符串格式设置:

print 'this is a tuple %s' % str((1, 2, 3))
# or
print 'this is a tuple %s' % ((1, 2, 3),)

请注意,这假设您使用的Python版本低于3.0。


7
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)

6

即使这个问题已经很老了并且有很多不同的答案,我仍然想添加恕我直言,这是最“ pythonic”的,也是可读/简洁的答案。

由于tuple锑已经正确地显示了常规打印方法,因此这是用于分别打印元组中的每个元素的附加功能,因为方嘉俊(Fong Kah Chun)已正确显示了该方法。%s语法。

有趣的是它在评论被只提到,但使用一个星号操作来解压缩所述元组产生完全的灵活性和可读性使用str.format方法分别打印元组元素时

tup = (1, 2, 3)
print('Element(s) of the tuple: One {0}, two {1}, three {2}'.format(*tup))

这也避免了在打印单元素元组时打印尾随逗号,这由Jacob CUI绕过replace。(即使恕我直言,如果要在打印时保留类型表示形式,则尾部逗号表示形式也是正确的):

tup = (1, )
print('Element(s) of the tuple: One {0}'.format(*tup))

5

我认为最好的方法是:

t = (1,2,3)

print "This is a tuple: %s" % str(t)

如果您熟悉printf样式格式,则Python支持其自己的版本。在Python中,这是通过将“%”运算符应用于字符串(模运算符的重载)来完成的,该运算符采用任何字符串并对其应用printf样式格式。

在我们的例子中,我们告诉它打印“ This is a tuple:”,然后添加一个字符串“%s”,对于实际的字符串,我们传入该tuple的字符串表示形式(通过调用str( t))。

如果您不熟悉printf样式格式,我强烈建议您学习,因为它非常标准。大多数语言都以某种方式支持它。


2

请注意,如果元组只有一项,则会在末尾添加逗号。例如:

t = (1,)
print 'this is a tuple {}'.format(t)

您会得到:

'this is a tuple (1,)'

在某些情况下,例如,您想获取要在mysql查询字符串中使用的带引号的列表,例如

SELECT name FROM students WHERE name IN ('Tom', 'Jerry');

您需要考虑在格式化后使用replace(',)',')')删除尾部逗号,因为元组可能只有1个项目,例如('Tom',),因此需要删除尾部逗号:

query_string = 'SELECT name FROM students WHERE name IN {}'.format(t).replace(',)', ')')

请建议您是否有适当的方法在输出中删除此逗号。


1
我通常更喜欢“这是一个元组({})”。format(','.join(map(str,t)))之类的东西。这样,您不必担心会与格式字符串中的现有逗号或括号混淆。

1
您不应该format()在数据库查询中使用。每个库中都有适用的方法。
ktalik

@ktalik您显然不明白这一点。format()与数据库查询无关。format()是python字符串操作的常用函数。看看docs.python.org/2/library/string.html,您将从中学习。记住与数据库查询无关。
崔雅各(CUI)2016年

使用format()从用户收集的值可能会导致SQL注入。在将输入值放入查询之前验证输入值更安全。有关更多信息,请参见以下准则:dev.mysql.com/doc/connector-python/en/…您还可以将参数值转换为数据库类型的字符串表示形式,然后将其粘贴到查询字符串中。看一下initd.org/psycopg/docs/usage.html,其中有一个带%运算符的反例和一个带execute()方法的解决方案,其中在参数args中传递了查询参数。
ktalik '16

1
@Paul Rooney请注意,我正在尝试解释,如果元组只有一项,则会在末尾添加逗号。如果使用不当会造成麻烦。格式当然也可以用于形成SQL查询。批评者来自哪里?
CUI Jacob CUI

2

除了其他答案中提出的方法外,从Python 3.6开始,您还可以使用文字字符串插值(f-strings):

>>> tup = (1,2,3)
>>> print(f'this is a tuple {tup}')
this is a tuple (1, 2, 3)

0

试试这个来获得答案:

>>>d = ('1', '2') 
>>> print("Value: %s" %(d))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

如果我们在()中只放入一个元组,它本身就会构成一个元组:

>>> (d)
('1', '2')

这意味着上面的打印语句看起来像:print(“ Value:%s”%('1','2'))这是一个错误!

因此:

>>> (d,)
(('1', '2'),)
>>> 

上面的内容将正确输入打印的参数。


0

对于python 3

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

0

您也可以尝试这个。

tup = (1,2,3)
print("this is a tuple {something}".format(something=tup))

您不能使用%something(tup)包装,并用元组拆包概念只是因为。


-5

谈话很便宜,请向您显示代码:

>>> tup = (10, 20, 30)
>>> i = 50
>>> print '%d      %s'%(i,tup)
50  (10, 20, 30)
>>> print '%s'%(tup,)
(10, 20, 30)
>>> 
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.