Issue
I am trying to do exactly the following:
>>> x = (1,2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x[0], x[1], y)
'1,2,hello'
However, I have a long x
, more than two items, so I tried:
>>> '%d,%d,%s' % (*x, y)
but it is syntax error. What would be the proper way of doing this without indexing like the first example?
Solution
str % ..
accepts a tuple as a right-hand operand, so you can do the following:
>>> x = (1, 2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x + (y,)) # Building a tuple of `(1, 2, 'hello')`
'1,2,hello'
Your try should work in Python 3, where Additional Unpacking Generalizations
is supported, but not in Python 2.x:
>>> '%d,%d,%s' % (*x, y)
'1,2,hello'
Answered By - falsetru
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.