veturi
veturi

Reputation: 1971

Why do I get "TypeError: not all arguments converted during string formatting" trying to format a tuple?

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.

Upvotes: 147

Views: 296938

Answers (12)

Jacob CUI
Jacob CUI

Reputation: 1345

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.

Upvotes: 5

JE_Muc
JE_Muc

Reputation: 5784

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

Upvotes: 13

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.

Upvotes: -1

TM.
TM.

Reputation: 111137

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

Upvotes: 8

Edan Maor
Edan Maor

Reputation: 10052

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.

Upvotes: 6

Vinay Sajip
Vinay Sajip

Reputation: 99510

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

Upvotes: 27

Tonechas
Tonechas

Reputation: 13743

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

Upvotes: 9

Antimony
Antimony

Reputation: 39491

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

Upvotes: 63

Fong Kah Chun
Fong Kah Chun

Reputation: 829

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

Upvotes: 55

Alex Martelli
Alex Martelli

Reputation: 882751

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

Upvotes: 223

123
123

Reputation: 315

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

Upvotes: -5

Esteban Küber
Esteban Küber

Reputation: 36862

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)

Upvotes: 8

Related Questions