【问题标题】:Python: Printing a variable with a float and then adding a £ sign [duplicate]Python:用浮点数打印变量,然后添加£符号[重复]
【发布时间】:2021-02-26 09:50:28
【问题描述】:

每当我打印出一个英镑符号后跟一个数字时,我都会收到此错误代码。

Traceback (most recent call last):
  File "main.py", line 65, in <module>
    print (u"\xA3" + total_cost)
TypeError: can only concatenate str (not "float") to str

这是代码。

total_cost == 10
print (u"\xA3" + total_cost)

我希望它输出 10 英镑。

有人可以帮忙吗?

【问题讨论】:

  • 最简单的方法是在print 中使用, 而不是+,或者然后将total_cost 转换为带有str(total_cost) 的字符串。如果要控制打印的位数,请使用 f-strings。

标签: python


【解决方案1】:

您可以尝试使用str() 函数将数字转换为字符串。不过,对于很多计算来说,它的效率不是很高,所以要小心:)

print(u"\xA3" + str(total_cost))

【讨论】:

    【解决方案2】:
    >>> print (u"\xA3", total_cost, sep='')
    £10
    

    【讨论】:

      【解决方案3】:

      试试这个:

      print (u"\xA3" + str(total_cost))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多