141

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

Mr_and_Mrs_D
  • 29,590
  • 35
  • 170
  • 347
veturi
  • 1,901
  • 2
  • 13
  • 16

16 Answers16

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

>>> # Python 3
>>> thetuple = (1, 2, 3)
>>> print(f"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.

mdahlman
  • 9,039
  • 4
  • 43
  • 72
Alex Martelli
  • 811,175
  • 162
  • 1,198
  • 1,373
59

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)
user443854
  • 6,474
  • 12
  • 46
  • 62
Antimony
  • 35,689
  • 10
  • 93
  • 100
  • I added a comment to this http://stackoverflow.com/a/26249755/1676424 for the case of 1 item tuple – Jacob CUI Oct 08 '14 at 05:29
  • I never knew why `%` is obsolete but I now always you `str.format` anyway, blindly. Nevermind that, I'm interested in what the full qualifier is, because the simple `{0}` isn't the full qualifier, but merely a position indicator. For an `int`, what I call the full qualifier would be `{0:d}` (or `{3:d}` for example, if the int to be printed occurs in the 4th position in the `str.format` method). I've tried printing a tuple using the `{0:s}` qualifier but it doesn't work. So, what's the full qualifier for something like a tuple? – Ray Mar 24 '16 at 11:53
  • 1
    @Ray That doesn't really make sense. There's lots of options you can specify, which can be found in the documentation. If you want to print something using `str` you can say `{!s}`, but this is the default, so it is unnecessary. If you want to use `repr` instead, you can do `{!r}`. Unlike with `%`, there is no need to say `d` for integers. – Antimony Mar 24 '16 at 14:02
  • 3
    I kind of like to % syntax as it is less verbose to my mind than the new format, and also very similar to c string formatting whick I know and love – Paulus Apr 24 '16 at 00:48
  • 1
    Note that, even on Python 3, the `%` isn't fully obsolete. In fact, `pylint` will even complain if you use the `.format` syntax within the `logging` module: https://stackoverflow.com/a/34634301/534238 – Mike Williamson Jun 20 '18 at 17:50
48

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

Fong Kah Chun
  • 701
  • 6
  • 6
  • I made the transition to using format() but this advantage of the % method (being able to format each element of a tuple and do conversions) is big so I think I will go back. Thanks. – Bill Jul 15 '17 at 18:03
  • 1
    You can specify the format for each element as well. '{:d}{:s}'.format(1, '2') – zk82 Jan 03 '18 at 15:58
  • 10
    The "asterisk unpacked" tuple works well with `.format`: `tup = (1,2,3); print('First: {}, Second: {}, Third: {}'.format(*tup))`. – m-dz Aug 23 '18 at 08:53
25
>>> 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.

Vinay Sajip
  • 90,050
  • 14
  • 168
  • 180
11

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))
JE_Muc
  • 4,980
  • 2
  • 22
  • 38
9

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.

TM.
  • 102,836
  • 30
  • 121
  • 127
8
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)
Esteban Küber
  • 35,226
  • 13
  • 82
  • 97
6

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)
Tonechas
  • 12,665
  • 15
  • 42
  • 74
5

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.

Edan Maor
  • 9,486
  • 17
  • 60
  • 91
4

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.

Jacob CUI
  • 1,239
  • 13
  • 10
  • 1
    I usually prefer something like 'this is a tuple ({})'.format(', '.join(map(str, t))). That way you don't have to worry about messing with existing commas or parenthesis in the format string. – Antimony Oct 09 '14 at 03:48
  • 1
    You shouldn't use `format()` in database queries. There are applicable methods for this in every library. – Konrad Talik Feb 12 '16 at 19:48
  • @ktalik you doesn't understand this obviously. format() has nothing to do with database queries. format() is common function to python string operation. Have a look at https://docs.python.org/2/library/string.html and you'll learn from it. Nothing to do with database queries remember. – Jacob CUI Feb 19 '16 at 21:35
  • Using `format()` with values collected from users might result with SQL injection. It is more secure to validate input values before putting them into the query. See these guidelines for more info: https://dev.mysql.com/doc/connector-python/en/connector-python-coding.html You can also cast parameter values to a database type string representation and then paste it to the query string. Take a look at http://initd.org/psycopg/docs/usage.html where you have a counterexample with `%` operator and a solution with `execute()` method where query parameters are being passed in method args. – Konrad Talik Feb 20 '16 at 22:36
  • 1
    @Paul Rooney Please note I'm trying to explain, a trailing comma will be added if the tuple only has one item. AND it'll cause trouble if not using correctly. Also format surely can be used to forming SQL queries. Where does the detractors come from?? – Jacob CUI Feb 22 '17 at 12:11
2

For python 3

tup = (1,2,3)
print("this is a tuple %s" % str(tup))
Wildhammer
  • 1,784
  • 1
  • 23
  • 25
0

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.

Yogi
  • 23
  • 3
0

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.

David Buck
  • 3,594
  • 33
  • 29
  • 34
0

Using f-string for a quick print in python3.

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

how much changed over the years. Now you can do this:

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

Results in: This is a Tuple (1,2,3).

Janneman
  • 329
  • 2
  • 11
-5

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)
>>> 
123
  • 297
  • 1
  • 6
  • 10