简体   繁体   English

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

[英]Printing tuple with string formatting in Python

So, i have this problem.所以,我有这个问题。 I got tuple (1,2,3) which i should print with string formatting.我得到了元组 (1,2,3) 我应该用字符串格式打印。 eg.例如。

tup = (1,2,3)
print "this is a tuple %something" % (tup)
>>> 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, ie the (thetuple,) part, is the key bit here.用感兴趣的元组作为唯一项制作一个单例元组,即(thetuple,)部分,是这里的关键。

Note that the % syntax is obsolete.请注意, %语法已过时。 Use str.format , which is simpler and more readable:使用str.format ,它更简单,更易读:

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

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.但是,使用.format()函数,您最终会得到一个冗长的语句。

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' .此外, '%'字符串运算符对我们验证数据类型也很有用,例如%s%d%i ,而 .format()仅支持两个转换标志'!s''!r'

>>> 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.注意(tup,)是一个包含元组的元组。 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)是括号中的表达式,计算结果为tup

(tup,) with the trailing comma is a tuple, which contains tup as is only member. (tup,)与后逗号是一个元组,其中包含tup作为是唯一成员。

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.请注意,这假设您使用的是早于 3.0 的 Python 版本。

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.尽管这个问题已经很老了并且有很多不同的答案,但我仍然想添加 imho 最“pythonic”并且可读/简洁的答案。

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.由于 Antimony 已经正确显示了一般的tuple打印方法,因此这是一个单独打印元组中每个元素的补充,正如 Fong Kah Chun 已使用%s语法正确显示%s

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 .有趣的是,它只在评论中提到过,但使用星号运算符来解包元组会在单独打印元组元素时使用str.format方法产生完全的灵活性和可读性。

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 .这也避免了在打印单元素元组时打印尾随逗号,正如 Jacob CUI 使用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))
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)

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.如果您熟悉printf样式格式,那么 Python 支持它自己的版本。 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.在 Python 中,这是使用应用于字符串的“%”运算符(模运算符的重载)完成的,它接受任何字符串并对其应用 printf 样式的格式。

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)).在我们的例子中,我们告诉它打印“这是一个元组:”,然后添加一个字符串“%s”,对于实际的字符串,我们传入一个元组的字符串表示(通过调用 str( t))。

If you're not familiar with printf style formatting, I highly suggest learning, since it's very standard.如果您不熟悉 printf 样式格式,我强烈建议您学习,因为它非常标准。 Most languages support it in one way or another.大多数语言都以一种或另一种方式支持它。

Besides the methods proposed in the other answers, since Python 3.6 you can also use Literal String Interpolation (f-strings):除了其他答案中提出的方法之外,从 Python 3.6 开始,您还可以使用文字字符串插值(f-strings):

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

Please note a trailing comma will be added if the tuple only has one item.请注意,如果元组只有一个项目,则会添加一个尾随逗号。 eg:例如:

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

and you'll get:你会得到:

'this is a tuple (1,)'

in some cases eg you want to get a quoted list to be used in mysql query string like在某些情况下,例如您想获得一个引用列表,以在 mysql 查询字符串中使用,例如

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:您需要考虑在格式化后使用 replace(',)', ')') 删除尾部逗号,因为元组可能只有 1 个像 ('Tom',) 这样的项目,因此需要删除尾部逗号:

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.请建议您是否有适当的方法在输出中删除此逗号。

For python 3对于蟒蛇 3

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

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!这意味着上面的打印语句看起来像: print("Value: %s" %('1', '2')) 这是一个错误!

Hence:因此:

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

Above will be fed correctly to the print's arguments.以上将被正确输入到打印的参数中。

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.由于使用元组打包和解包的概念,您不能将%something(tup)一起使用。

Using f-string for a quick print in python3.使用 f-string 在 python3 中快速打印。

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

how much changed over the years.这些年来发生了多少变化。 Now you can do this:现在你可以这样做:

tup = (1,2,3)
print(f'This is a Tuple {tup}.')

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM