簡體   English   中英

打印格式字符串函數和變量(python)

[英]printing format string function and variable (python)

函數和變量的定義:

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 """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)))

我收到的錯誤消息是“%d格式:是一個數字,不是一個元組。請幫助我修復它。我真的是編程新手...或者只是不能打包一個變量和一個調用函數變成相同的格式打印?

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

我在其中通過將元組(start_point, )到函數的結果中來創建新的元組。


在python 3中,您可以*解壓元組

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

考慮添加*以便解開元組(python 3.x解決方案):

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

如果您使用的是python 2.x,則可以輸入:

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)

使用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]))

產量

startpoint : 1000.0 
    beans:       500000.0  
    jar :        500.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM