python格式函数有问题吗

2024-10-01 17:37:54 发布

您现在位置:Python中文网/ 问答频道 /正文

inputoutput

var1 = 'ketchup'
regularprice = 12.80
discount_percentage = 0.27
finalprice = regularprice*(1-discount_percentage)

print('${:.2f} is the sale price of ketchup.'. format(finalprice))

print('${:.2f}is the sale price of' + ' ' + var1 + '.'. format(finalprice))

如上所示,我发现添加变量的第二个“print”无法正确显示。格式化功能不起作用

谁能给我一些提示吗?:)


Tags: oftheformatinputoutputisdiscountsale
3条回答

发生这种情况的原因是运算符优先级.+结合更紧密。要在由多个片段组成的字符串上使用.format(),必须使用括号

不过,在这种情况下,最好使用.format输入两个值:

print('${:.2f} is the sale price of {:s}.'.format(finalprice, var1))

或者,由于s格式是默认格式:

print('${:.2f} is the sale price of {}.'.format(finalprice, var1))

如果您使用的是最新版本的Python,还可以使用f字符串:

print(f'${finalprice:.2f} is the sale price of {var1}.')

实际情况是:

print('${:.2f} is the sale price of ' + var1 + ('.'.format(finalprice)))

您需要的是:

print(('${:.2f} is the sale price of ' + var1 + '.').format(finalprice))

请注意括号

使用以下命令:

print('${:.2f} is the sale price of'.format(finalPrice) + varl + '.')

通过您的代码,Python将理解您正在为第三个字符串元素'.'使用format函数,该元素没有任何格式

相关问题 更多 >

    热门问题