Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does .format(function()) not work, but % prints the value?

Code that I wrote:

def ball(f):  
    py_ball = f * 5
    u_ball = py_ball / 10  
    return py_ball, u_ball
print("py ball: {}, u ball: {}".format(ball(100)))

When I use str.format, it throws an exception:

Traceback (most recent call last):
  File "rear.py", line 5, in 
    print("py ball: {}, u ball: {}".format(ball(100)))
IndexError: tuple index out of range

But if I use % formatting:

print("py ball: %d, u ball: %d" % ball(100))

it works just fine and produces:

py ball: 500, u ball: 50
like image 733
Saklain55 Avatar asked Mar 21 '26 10:03

Saklain55


1 Answers

str.format() takes separate arguments for each slot, while % accepts a tuple or a single value. ball() returns a tuple, and that's a single argument as far as str.format() is concerned. Because your template has 2 slots, there is an argument missing for that second slot.

You have two options: Either accept a single argument for .format() and use formatting instructions to extract the nested elements, or pass in the tuple as separate arguments.

The latter can be done with the *expr call notation:

print("py ball: {}, u ball: {}".format(*ball(100)))

but the formatting specification lets you also address tuple elements:

print("py ball: {0[0]}, u ball: {0[1]}".format(ball(100)))

I used explicit numbering here to indicate that just one argument is expected, in position 0; 0[0] takes the first element of the tuple, 0[1] takes the second.

like image 66
Martijn Pieters Avatar answered Mar 22 '26 22:03

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!