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)
>>> 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.
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.
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)
For python 3
tup = (1,2,3)
print("this is a tuple %s" % str(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)
>>>
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)