Printing tuple with string formatting in Python
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'
.
>>> # 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.
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)