问题描述
有人可以告诉我这个代码有什么问题吗? def format_money_value(num):
返回u'{0:.2f}'。format(num)
它给我以下错误:
类型为'unicode'的对象的未知格式代码'f'
/ pre>
我正在运行Django 1.5
谢谢
解决方案在你的情况下
num
是一个unicode字符串,不支持f
格式修饰符:>>> '{0:.2f}'。format(u5.0)
追溯(最近的最后一次呼叫):
文件< stdin>,第1行,< module>
ValueError:'unicode'类型的对象的未知格式代码'f'
你可以修正将转换成
float
的错误:>> ;> '{0:.2f}'。format(float(u5.0))
'5.00'
正如mgilson所指出的那样
'{0:.2f}'。format(num)
,格式
方法调用num .__格式__(。2f)
。这导致str
或unicode
的错误,因为他们不知道如何处理此格式说明符。请注意,f
的含义作为对象的实现留下。对于数字类型,它意味着将数字转换为浮点字符串表示,但其他对象可能有不同的约定。
如果您使用
%
格式化运算符的行为是不同的,因为在这种情况下,%f
直接调用__ float __
获取对象的浮点表示。
这意味着当使用%
-style格式化f
具体含义,即转换为浮点字符串表示。can someone tell me what is wrong with this code...
def format_money_value(num): return u'{0:.2f}'.format(num)
It gives me the following error:
Unknown format code 'f' for object of type 'unicode'
I'm running Django 1.5
Thank you
解决方案In your case
num
is a unicode string, which does not support thef
format modifier:>>> '{0:.2f}'.format(u"5.0") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Unknown format code 'f' for object of type 'unicode'
You can fix the error making the conversion to
float
yourself:>>> '{0:.2f}'.format(float(u"5.0")) '5.00'
As pointed out by mgilson when you do
'{0:.2f}'.format(num)
, theformat
method of the strings callsnum.__format__(".2f")
. This results in an error forstr
orunicode
, because they don't know how to handle this format specifier. Note that the meaning off
is left as an implementation for the object. For numeric types it means to convert the number to a floating point string representation, but other objects may have different conventions.If you used the
%
formatting operator the behaviour is different, because in that case%f
calls__float__
directly to obtain a floating point representation of the object.Which means that when using%
-style formattingf
does have a specific meaning, which is to convert to a floating point string representation.这篇关于'unicode'类型的对象的未知格式代码'f'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!