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

所以,我有这个问题。我有元组(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在这里输了,所以如果你们能指出我正确的方向:)

So, i have this problem. I got tuple (1,2,3) which i should print with string formatting. eg.

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

and this should print tuple representation with brackets, like

This is a tuple (1,2,3)

But I get TypeError: not all arguments converted during string formatting instead.

How in the world am I able to do this? Kinda lost here so if you guys could point me to a right direction :)


回答 0

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

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

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

Making a singleton tuple with the tuple of interest as the only item, i.e. the (thetuple,) part, is the key bit here.


回答 1

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

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

Note that the % syntax is obsolete. Use str.format, which is simpler and more readable:

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

回答 2

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

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

Many answers given above were correct. The right way to do it is:

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

However, there was a dispute over if the '%' String operator is obsolete. As many have pointed out, it is definitely not obsolete, as the '%' String operator is easier to combine a String statement with a list data.

Example:

>>> tup = (1,2,3)
>>> print "First: %d, Second: %d, Third: %d" % tup
First: 1, Second: 2, Third: 3

However, using the .format() function, you will end up with a verbose statement.

Example:

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

Further more, '%' string operator also useful for us to validate the data type such as %s, %d, %i, while .format() only support two conversion flags: '!s' and '!r'.


回答 3

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

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

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

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

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

Note that (tup,) is a tuple containing a tuple. The outer tuple is the argument to the % operator. The inner tuple is its content, which is actually printed.

(tup) is an expression in brackets, which when evaluated results in tup.

(tup,) with the trailing comma is a tuple, which contains tup as is only member.


回答 4

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

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。

This doesn’t use string formatting, but you should be able to do:

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

If you really want to use string formatting:

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

Note, this assumes you are using a Python version earlier than 3.0.


回答 5

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)

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

Even though this question is quite old and has many different answers, I’d still like to add the imho most “pythonic” and also readable/concise answer.

Since the general tuple printing method is already shown correctly by Antimony, this is an addition for printing each element in a tuple separately, as Fong Kah Chun has shown correctly with the %s syntax.

Interestingly it has been only mentioned in a comment, but using an asterisk operator to unpack the tuple yields full flexibility and readability using the str.format method when printing tuple elements separately.

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

This also avoids printing a trailing comma when printing a single-element tuple, as circumvented by Jacob CUI with replace. (Even though imho the trailing comma representation is correct if wanting to preserve the type representation when printing):

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

回答 7

我认为最好的方法是:

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样式格式,我强烈建议您学习,因为它非常标准。大多数语言都以某种方式支持它。

I think the best way to do this is:

t = (1,2,3)

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

If you’re familiar with printf style formatting, then Python supports its own version. In Python, this is done using the “%” operator applied to strings (an overload of the modulo operator), which takes any string and applies printf-style formatting to it.

In our case, we are telling it to print “This is a tuple: “, and then adding a string “%s”, and for the actual string, we’re passing in a string representation of the tuple (by calling str(t)).

If you’re not familiar with printf style formatting, I highly suggest learning, since it’s very standard. Most languages support it in one way or another.


回答 8

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

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(',)', ')')

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

Please note a trailing comma will be added if the tuple only has one item. e.g:

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

and you’ll get:

'this is a tuple (1,)'

in some cases e.g. you want to get a quoted list to be used in mysql query string like

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

you need to consider to remove the tailing comma use replace(‘,)’, ‘)’) after formatting because it’s possible that the tuple has only 1 item like (‘Tom’,), so the tailing comma needs to be removed:

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

Please suggest if you have decent way of removing this comma in the output.


回答 9

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

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

Besides the methods proposed in the other answers, since Python 3.6 you can also use Literal String Interpolation (f-strings):

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

回答 10

试试这个来获得答案:

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

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

Try this to get an answer:

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

If we put only-one tuple inside (), it makes a tuple itself:

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

This means the above print statement will look like: print(“Value: %s” %(‘1’, ‘2’)) which is an error!

Hence:

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

Above will be fed correctly to the print’s arguments.


回答 11

对于python 3

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

For python 3

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

回答 12

您也可以尝试这个。

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

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

You can try this one as well;

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

You can’t use %something with (tup) just because of packing and unpacking concept with tuple.


回答 13

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

>>> tup = (10, 20, 30)
>>> i = 50
>>> print '%d      %s'%(i,tup)
50  (10, 20, 30)
>>> print '%s'%(tup,)
(10, 20, 30)
>>> 

Talk is cheap, show you the code:

>>> tup = (10, 20, 30)
>>> i = 50
>>> print '%d      %s'%(i,tup)
50  (10, 20, 30)
>>> print '%s'%(tup,)
(10, 20, 30)
>>> 

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。