Lars Steen
Lars Steen

Reputation: 759

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

Upvotes: 3

Views: 125

Answers (1)

Ethan Furman
Ethan Furman

Reputation: 69031

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().

Upvotes: 3

Related Questions