Python 如何使用变量值打印文本

Python 如何使用变量值打印文本,python,printing,Python,Printing,我编写了一个小函数来检查两个值中哪一个最接近零。我遇到的问题是最后的print语句:我希望它打印文本,后跟它确定的最接近的值 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,yhig

我编写了一个小函数来检查两个值中哪一个最接近零。我遇到的问题是最后的print语句:我希望它打印文本,后跟它确定的最接近的值

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

θ的最接近值为


这种特定的语法在其他情况下有效,但在这里不起作用,我不确定为什么。如果您能解释一下为什么不起作用以及如何修复它,我们将不胜感激,谢谢

您试图使用字符串模板,但未指定在模板中填充变量的位置

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

好的,谢谢!现在这很好用。因此%f是一个标记,它会将%后面的任何内容的浮点值放在“标记”后面。请阅读此文件,了解有关字符串格式的详细信息-<代码>%f将值打印为浮点数。如果要打印字符串,请使用
%s