简体   繁体   English

'unicode'类型对象的未知格式代码'f'

[英]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. 这会导致strunicode出错,因为他们不知道如何处理这种格式说明符。 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 确实具有特定含义,即转换为浮点字符串表示。

what .format() do 什么.format()呢

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类型派生的任何类型,如strunicode 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.

相关问题 类型为&#39;str&#39;的对象的未知格式代码&#39;f&#39;-Folium - Unknown format code 'f' for object of type 'str'- Folium 在代码中格式化不断导致 ValueError: Unknown format code 'f' for object of type 'str'? - Formatting in a code constantly causes the ValueError: Unknown format code 'f' for object of type 'str'? ValueError:类型为&#39;str&#39;的对象的未知格式代码&#39;f&#39;-为什么第二次却不是第一次? - ValueError: Unknown format code 'f' for object of type 'str' - why do I get this the second time but not the first time? 在我的情况下,“str”类型的 object 的“未知格式代码 'f' 是什么意思? - What does "Unknown format code 'f' for object of type 'str' mean in my case? “str”类型对象的未知格式代码“g” - Unknown format code 'g' for object of type 'str' 类型“ str”的对象的未知格式代码“ b” - Unknown format code 'b' for object of type 'str' 类型为“布尔”的对象的未知格式代码“ r” - Unknown format code 'r' for object of type 'bool' ValueError:类型为“ str”的对象的未知格式代码“ g” - ValueError: Unknown format code 'g' for object of type 'str' ValueError: 类型“str”的对象的格式代码“e”未知 - ValueError: Unknown format code 'e' for object of type 'str' 使用“{0:d}”.format 的字符串格式为“float”类型的对象提供未知格式代码“d” - String formatting with “{0:d}”.format gives Unknown format code 'd' for object of type 'float'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM