Dennis
Dennis

Reputation: 269

How to unpack and print a tuple

I am a beginner in Python (3.x), this is my first post here, and I am trying to unpack a tuple, then print it with a certain format (my words may not be quite right). Here is what I have:

w = 45667.778
x = 56785.55
y = 34529.4568
z = 789612.554

nums = (w, x, y, z)
hdr62 = '{:>15} {:>15} {:>15} {:>15}'

print(tuple('${:,.0f}'.format(num).rjust(12, ' ') for num in nums))

What/how do I alter to unpack and then use the hdr62 format to print the tuple?

Upvotes: 3

Views: 1529

Answers (2)

poke
poke

Reputation: 388463

Maybe I’m missing things, but if you just want to format the tuple nums according to the hdr62 format, then you can just call str.format on it and pass in the numbers as unpacked tuple:

>>> print(hdr62.format(*nums))
      45667.778        56785.55      34529.4568      789612.554

If you actually want to run another format on the tuple items first, you can do that separately:

>>> ['${:,.0f}'.format(n) for n in nums]
['$45,668', '$56,786', '$34,529', '$789,613']
>>> print(hdr62.format(*['${:,.0f}'.format(n) for n in nums]))
        $45,668         $56,786         $34,529        $789,613

Upvotes: 3

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477891

Based on your question and the comments below, you can first use the tuple comprehension to format your numbers and then call the formatting. The format call can be done with an asterisk (*), so:

nums2 = tuple('${:,.0f}'.format(num).rjust(12, ' ') for num in nums)
print(hdr62.format(*nums2))

If you call a function and use an asterisk, the parameter (which should be a sequence) behind the curtains Python unpacks the sequence and feed it as separate parameters, so in this case:

nums2 = tuple('${:,.0f}'.format(num).rjust(12, ' ') for num in nums)
print(hdr62.format(*nums2))

is equivalent to:

nums2 = tuple('${:,.0f}'.format(num).rjust(12, ' ') for num in nums)
print(hdr62.format(nums[0],nums[1],nums[2],nums[3]))

Upvotes: 1

Related Questions