print ('%0.2f'+ % userUSD + '= %0.2f' + %Euro + 'Euro')

I'm using python 3.3 and while making a very simple currency converter I've stumbled upon this syntax error. Could you guys tell me how could I fix this and write the right way to print the floating point number in this case?

有帮助吗?

解决方案

The syntax error is because you're using both the + and % operators in a row. When you use % for string formatting, you don't want + in between the format string and its arguments.

So, the most basic fix would be to get rid of the extra + characters:

print ('%0.2f' % userUSD + '= %0.2f' % Euro + 'Euro')

However, it would probably make more sense to combine the format strings together, and do just one formatting operation:

print('%0.2f = %0.2f Euro' % (userUSD, Euro))

In new code though it's generally recommended to use the more capable str.format formatting system, rather than the % operator:

print('{:.2f} = {:.2f} Euro'.format(userUSD, Euro))

其他提示

print ('%0.2f USD = %0.2f Euro' % (USD, Euro))

This is the proper way to write Python 3 formatted strings, using str.format():

print("{:0.2f} = {:0.2f} Euro".format(userUSD, Euro))

This breaks down to taking each positional value and formatting it with two decimal places, just like you would with % above.

print ('%0.2f USD = %0.2f Euro' % (USD, Euro))

The formatted string comes inside a single pair of quotations. The variables come then as a list after a % symbol.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top