简体   繁体   English

浮点数python 3+

[英]Float numbers python 3+

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. 我正在使用python 3.3,并且在制作一个非常简单的货币转换器时,偶然发现了此语法错误。 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: 尽管通常建议在新代码中使用功能更强大的str.format格式化系统,而不是%运算符:

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() : 这是使用str.format()编写Python 3格式的字符串的正确方法:

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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