[英]Unknown format code 'f' for object of type 'unicode'
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 我正在运行Django 1.5
Thank you 谢谢
In your case num
is a unicode string, which does not support the f
format modifier: 在你的情况下, num
是一个unicode字符串,它不支持f
格式修饰符:
>>> '{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: 您可以修复错误,使转换float
:
>>> '{0:.2f}'.format(float(u"5.0"))
'5.00'
As pointed out by mgilson when you do '{0:.2f}'.format(num)
, the format
method of the strings calls num.__format__(".2f")
. 正如mgilson指出的那样,当你执行'{0:.2f}'.format(num)
,字符串的format
方法调用num.__format__(".2f")
。 This results in an error for str
or unicode
, because they don't know how to handle this format specifier. 这会导致str
或unicode
出错,因为他们不知道如何处理这种格式说明符。 Note that the meaning of f
is left as an implementation for the object. 请注意, f
的含义保留为对象的实现。 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. 如果使用%
格式化运算符,则行为不同,因为在这种情况下, %f
直接调用__float__
以获取对象的浮点表示。 Which means that when using %
-style formatting f
does have a specific meaning, which is to convert to a floating point string representation. 这意味着当使用%
-style格式时f
确实具有特定含义,即转换为浮点字符串表示。
str.format
method calls __format__()
method of related type. str.format
方法调用相关类型的__format__()
方法。 That means 这意味着
<type>.__format__(<value>, <spec>)
above method accepts the same type argument as first value, and accepts a suitable spec
type as second one. 上面的方法接受与第一个值相同的类型参数,并接受合适的spec
类型作为第二个。 Like, 喜欢,
str.__format__('1', 's')
int.__format__(1, 'f')
float.__format__(1.00, 'f')
str.__format__
accepts any type that is derived from str
type, like str
or unicode
. str.__format__
接受从str
类型派生的任何类型,如str
或unicode
。 Spec value must be a valid formatter that is usable of that type. 规范值必须是可用于该类型的有效格式化程序。 Following will raise an error 以下将引发错误
str.__format__('1', 'f')
ValueError: Unknown format code 'f' for object of type 'str'
since floating point
formatting is not a suitable format type fot string. 因为floating point
格式化不是合适的格式类型fot string。 Likewise following will raise an error too 同样,以下也会引发错误
float.__format__(1.00, 's')
ValueError: Unknown format code 's' for object of type 'float'
since float is a numeric
type and can not formatted as a string
. 因为float是一个numeric
类型,不能格式化为string
。 But following are all valid: 但以下都是有效的:
float.__format__(1.00, 'g')
float.__format__(1.00, 'f')
similarly following will raise an exception 以下同样会引发异常
float.__format__(1.00, 'd')
ValueError: Unknown format code 'd' for object of type 'float'
since formatting a float point to a decimal value will cause precision values to be lost. 因为将浮点数格式化为十进制值将导致精度值丢失。 But formatting an int
to float
will not cause a such thing, so it is a valid conversion: 但是将int
格式化为float
不会导致这样的事情,所以它是一个有效的转换:
int.__format__(1, 'f')
So .format()
is limeted to specs
that is available to the related formatting type
. 因此.format()
可用于相关格式type
可用的specs
。 You must parse your value as @Bakuriu defined: 你必须解析你的价值@Bakuriu定义:
'{0:.2f}'.format(float(u"5.0"))
The scenario where you are re-formatting a string (unicode or otherwise) as a float string is not very safe. 您将字符串(unicode或其他)重新格式化为浮点字符串的方案不是很安全。 You should first convert the string to a numeric representation and only if that succeeds should you format it as a string again. 您应该首先将字符串转换为数字表示形式,并且只有在成功时才应将其格式化为字符串。 You are not in control of the data that comes into your program so you should be sure to validate it coming in. 您无法控制进入程序的数据,因此您应该确保验证它的进入。
If you choose to leave it as a string you can use this: 如果您选择将其保留为字符串,则可以使用:
return u"{:.2f}".format(num) if num.isnumeric() else u"{}".format(num)
If you have already converted the string into a numeric format, you can adjust your formatter like this: 如果您已将字符串转换为数字格式,则可以像下面这样调整格式化程序:
return u"{:.2f}".format(num) if isinstance(num, NumberTypes) else u"{}".format(num)
I've faced a similar problem as the OP, when num
was a numerical answer returned by one of my libraries, whose implementation detais got forgotten: 我遇到了与OP类似的问题,当num
是我的一个库返回的数字答案时,其实现细节被遗忘了:
>>> num
-4132.56528214700
>>> u'{0:.4g}'.format(num)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'g' for object of type 'unicode'
I was really puzzled because num
behaved like a float but after testing @Bakuriu 's solution, I've found out it wasn't a float: 我真的很困惑,因为num
表现得像个漂浮物,但在测试了@Bakuriu的解决方案后,我发现它不是浮点数:
>>> type(num)
<class 'sympy.core.numbers.Float'>
So @Bakuriu 's solution was right on target for my case: 所以@Bakuriu的解决方案正好适用于我的案例:
>>> u'{0:.4g}'.format(float(num))
u'-4133'
Therefore, the error can be due to types that display/calculate like but aren't really floats. 因此,错误可能是由于显示/计算类型但不是真正浮动的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.