简体   繁体   English

在python中返回格式化的字符串

[英]Returning a formatted string in python

def compute_tax(gross_pay):
    tax = gross_pay * 0.15
    return "PHP {:,.2f}".format(tax)

I am trying to return the tax in a formatted string, but it generates an error TypeError: can't multiply sequence by non-int of type 'float' Why does this happen?我正在尝试以格式化字符串返回税款,但它会生成错误TypeError: can't multiply sequence by non-int of type 'float'为什么会发生这种情况? The gross_pay is float. Gross_pay 是浮动的。 I also tested this function using pytest and it worked fine.我还使用pytest测试了这个函数,它运行良好。 But when I run the program itself, it crashes.但是当我运行程序本身时,它会崩溃。 What am I doing wrong?我究竟做错了什么?

If your other function is returning gross_pay as a string, you can always convert it to a float.如果您的其他函数将 Gross_pay 作为字符串返回,您始终可以将其转换为浮点数。

def compute_tax(gross_pay):
    gross_pay = float(gross_pay)
    tax = gross_pay * 0.15
    return "PHP {:,.2f}".format(tax)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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