Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use a function call inside the format method, when formatting a string

I've got some code:

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates

start_point = 10000

#print ('We\'d have {0} beans, {1} jars, and {2} crates.'
        .format(secret_formula(start_point)))

print ('We\'d have %d beans, %d jars, and %d crates.'
        % secret_formula(start_point))

My question is regarding the two last statements. The one that is commented out does not work (returns an index out of range error), but the other one does. Why is that? And how can I make the commented out statement work?

Thanks in advance :)

Lars

like image 791
Lars Steen Avatar asked May 09 '26 14:05

Lars Steen


1 Answers

The commented out line should be

print ('We\'d have {0} beans, {1} jars, and {2} crates.'
        .format(*secret_formula(start_point)))

Notice the * before secret_formula(...) -- it tells Python to unpack the result when passing the values to format().

like image 200
Ethan Furman Avatar answered May 11 '26 04:05

Ethan Furman



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!