Reputation: 1466
This may be the simplest of questions. But I tried to print the individual values of the tuple in the following manner.
mytuple=('new','lets python','python 2.7')
>>> print "%{0} experience, %{1} with %{2} " %mytuple
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
print "%{0} experience, %{1} with %{2} " %mytuple
ValueError: unsupported format character '{' (0x7b) at index 1
I want to print the output to be like the following.
"new experience, lets python with python 2.7"
I don't remember where it was it done. Is it called unpacking tuple values, printing formatted tuples.
Upvotes: 2
Views: 3252
Reputation: 427
I've come across the problem with tuples formatting and came to a solution:
mydate = (9, 1) print("The date is ({date[0]}, {date[1]})".format(date=mydate)) The date is (9, 1)
(It seems the solution is for only some problems, with fixed tuples that we know of.)
Upvotes: 0
Reputation: 315
Only need to modify a little:
>>> mytuple=('new','lets python','python 2.7')
>>> print "%s experience, %s with %s " %mytuple
new experience, lets python with python 2.7
>>>
Upvotes: 0
Reputation: 11
you just mixed up printf
and str.format
, you need choose one of them:
>>> tuple1 = ("hello", "world", "helloworld")
>>> print("%s, %s, %s" % tuple1)
or:
>>> tuple1 = ("hello", "world", "helloworld")
>>> print("{}, {}, {}".format(*tuple1))
Upvotes: 1
Reputation: 2404
You can any one of the method. However the format thing is simpler and you can manage it more easily.
>>> a = '{0} HI {1}, Wassup {2}'
>>> a.format('a', 'b', 'c')
'a HI b, Wassup c'
>>> b = ('a' , 'f', 'g')
>>> a.format(*b)
'a HI f, Wassup g'
Upvotes: 1
Reputation: 471
You could use format method and asterisk to solve the problem.
please refer to this link for further details
>>mytuple=('new','lets python','python 2.7')
>>print "{0} experience, {1} with {2} ".format(*mytuple)
new experience, lets python with python 2.7
Upvotes: 1
Reputation: 369444
Instead of mixing printf
-style formating and str.format
, choose one:
>>> mytuple = ('new','lets python','python 2.7')
>>> print "%s experience, %s with %s" % mytuple
new experience, lets python with python 2.7
>>> print "{0} experience, {1} with {2}".format(*mytuple)
new experience, lets python with python 2.7
Upvotes: 5