简体   繁体   中英

printing format string function and variable (python)

definition of function & variable:

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

start_point = 10000 / 10

print statement:

print """crazy different style:
startpoint: %d\n
beans:\t\t %d\n
jars:\t\t %d\n
crates:\t\t %d\n
""" % (start_point, (secret_formula(start_point)))

The error message I get is " %d format: a number is required, not a tuple. Please help me fix it. I´m really new to programming...or is it just not possible to pack a variable and a called function into the same formattet print?

a variant for in python 2:

print """crazy different style:
startpoint: %d\n
beans:\t\t %d\n
jars:\t\t %d\n
crates:\t\t %d\n
""" % ((start_point, ) + secret_formula(start_point))

where i create a new tuple by adding the tuple (start_point, ) to the result of your function.


in python 3 you can unpack the tuple with a * :

print("""crazy different style:
startpoint: %d\n
beans:\t\t %d\n
jars:\t\t %d\n
crates:\t\t %d\n
""" % (start_point, *secret_formula(start_point)))

Consider adding * in order to unpack the tuple (python 3.x solution):

print ("""crazy different style:
startpoint: %d\n
beans:\t\t %d\n
jars:\t\t %d\n
crates:\t\t %d\n
""" % (start_point, *(secret_formula(start_point))))

If you're using python 2.x can type:

start_point = 10000 / 10
res = secret_formula(start_point)
print """crazy different style:
startpoint: %d\n
beans:\t\t %d\n
jars:\t\t %d\n
crates:\t\t %d\n
""" % (start_point, res[0], res[1], res[2])
#According to zen of python Explicit is better than implicit, so

bs, js, cs = secret_formula(start_point)

print """crazy different style:
startpoint: %d\n
beans:\t\t %d\n
jars:\t\t %d\n
crates:\t\t %d\n
""" % (start_point, bs, js, cs)

Working on python 3

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

start_point = 10000 / 10

print ("startpoint : {0} \n \
       beans:\t\t {1}  \n \
       jar :\t\t {2}".format(start_point,*secret_formula(start_point)[:2]))

output

startpoint : 1000.0 
    beans:       500000.0  
    jar :        500.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM