簡體   English   中英

如何使用變量值打印文本

[英]How to print text with the value of a variable

我編寫了一個小函數來檢查兩個值中的哪個最接近零。 我遇到的問題是最后的打印語句:我希望它打印文本,然后打印確定的最接近的值。

def closestcheck(ylow, yhigh, ylist, xlist):
    ynew = (ylow + yhigh) / 2
    #The following 2 prints are purely to check the calculations are correct
    print(ynew)
    print(ylow,yhigh)
    if ynew > 0:
        print('The closest value of theta is' % ylow)
    else:
        print('The closest value of theta is' % yhigh)

closestcheck(y0[-1],y0[-2],y0,x0)

它將打印文本但不打印數字

6.13910823576e-07

-3.46867223283e-06 4.69649387998e-06

theta的最接近值是

這種特定的語法在其他情況下也有效,但在這里卻不起作用,我不確定原因。 非常感謝您解釋一下為什么此方法不起作用以及如何解決它,謝謝!

您正在嘗試使用字符串模板,但未指定模板中的何處填充變量。

if ynew>0:
    print('The closest value of theta is %f' % ylow)
else:
    print('The closest value of theta is %f' % yhigh)

當你在它,用繩子模板%那種聞起來像奶奶的亞麻櫥櫃這些天。 建議改用此方法:

y_closest = ylow if ynew > 0 else yhigh
print('The closest value of theta is {y}'.format(y=y_closest))

暫無
暫無

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

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