147

I want to use %-style string formatting to print a tuple:

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

I expect it to print like This is a tuple: (1,2,3)., but instead I get an error that says TypeError: not all arguments converted during string formatting.

What is wrong, and how do I fix it?


In editing this question for clarity and modernization, I preserved one interesting aspect of the original example: the parentheses around tup. These are not necessary for the % syntax, and also do not create a tuple. It's possible that OP understood that the tuple wrapping (described in the answers here) was necessary, but simply got it wrong. For more information on that issue, see How to create a "singleton" tuple with only one element.

12 Answers 12

222
>>> 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
  • 1
    In Python 3 print is a function, not a statement, so you have to write print(....). May 16, 2020 at 17:09
62

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))
5
  • I added a comment to this stackoverflow.com/a/26249755/1676424 for the case of 1 item tuple
    – Jacob CUI
    Oct 8, 2014 at 5: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, 2016 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, 2016 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, 2016 at 0: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: stackoverflow.com/a/34634301/534238 Jun 20, 2018 at 17:50
52

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)

The % string operator is still supported in Python 3.x, and makes it easier to format a tuple (or list) as separate values. Using .format for this case will require some additional work - either the values need to be passed as separate arguments, or the sequence will need to be indexed:

>>> tup = (1,2,3)
>>> print("First: %d, Second: %d, Third: %d" % tup)
First: 1, Second: 2, Third: 3
>>> print('First: {}, Second: {}, Third: {}'.format(1,2,3))
First: 1, Second: 2, Third: 3
>>> print('First: {0[0]}, Second: {0[1]}, Third: {0[2]}'.format(tup))
First: 1, Second: 2, Third: 3

The % operator is also useful for validating the type of the arguments, using different formatting codes (%s, %d, %i), while .format() only supports two conversion flags: '!s' and '!r'.

4
  • 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, 2017 at 18:03
  • 2
    You can specify the format for each element as well. '{:d}{:s}'.format(1, '2')
    – zk82
    Jan 3, 2018 at 15:58
  • 14
    The "asterisk unpacked" tuple works well with .format: tup = (1,2,3); print('First: {}, Second: {}, Third: {}'.format(*tup)).
    – m-dz
    Aug 23, 2018 at 8:53
  • 1
    This is wrong. The .format syntax does allow for type-checking. !s and !r are a separate feature. We can specify the required type with e.g. '{:d}'.format(x), which will work only when x is an integer. Apr 4 at 0:58
27
>>> tup = (1, 2, 3)
>>> print "Here it is: %s" % (tup,)
Here it is: (1, 2, 3)
>>>

Here, (tup,) - with the trailing comma - 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. Without the trailing comma, (tup) is the same as tup - the parentheses are just normal grouping parentheses.

12

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

Besides the methods proposed in the other answers, since Python 3.6 we 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).
1
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)
8

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),))
0
6

Try explicitly converting the tuple to string first:

t = (1,2,3)

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

Python supports using the % operator on strings to do printf-style formatting on strings. Here, since we use a %s placeholder, it makes sense to pass a string (created with str(t)) for the value.

5

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.

5
  • 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 9, 2014 at 3:48
  • 1
    You shouldn't use format() in database queries. There are applicable methods for this in every library. Feb 12, 2016 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 docs.python.org/2/library/string.html and you'll learn from it. Nothing to do with database queries remember.
    – Jacob CUI
    Feb 19, 2016 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: dev.mysql.com/doc/connector-python/en/… You can also cast parameter values to a database type string representation and then paste it to the query string. Take a look at 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. Feb 20, 2016 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, 2017 at 12:11
-1

You can try this one as well;

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.