小能豆

Python: Printing a variable with a float and then adding a £ sign

python

Whenever I go to print out a GBP sign followed by a number I get this error code.

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

This is the code.

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

I would like for it to output £10.

Can someone help please?


阅读 70

收藏
2023-11-27

共1个答案

小能豆

The issue here is that you are trying to concatenate a Unicode string (u"\xA3") with a floating-point number (total_cost). To resolve this, you need to convert the total_cost to a string before concatenating. Also, you used == (comparison operator) instead of = (assignment operator) when assigning the value to total_cost. Here’s the corrected code:

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

This code will output:

£10

By using str(total_cost), you convert the floating-point number to a string, allowing you to concatenate it with the Unicode pound sign.

2023-11-27