我想要什么
在此示例中,我希望不使用来查看unicode字符串print
:
In [1]: a = u's·A/m'
In [2]: type(a)
Out[2]: str
In [3]: a
Out[3]: 's\xc2\xb7A/m'
In [4]: print a
s·A/m
如何强制字符串__repr__
不显示s\xc2\xb7A/m
,但是s·A/m
呢?
用例是什么?
我有一个代表与其单位关联的数字的类,例如:
class MyNumber(float):
def __new__(cls, ...):
...
def __repr__(self):
return str(self) + str(self.units)
当我在IPython中工作时,我想快速查看实例的内容:
>>> a = MyNumber('23.43', ampere=1, second=1, meter=-1)
>>> a
23.43 s·A/m
相反,我得到一个例外:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 11: ordinal not in range(128)
而且,如果我尝试手动查看我的内容,则会__repr__
得到以下信息:
>>>a.__repr__()
23.43 s\xc2\xb7A/m
而不是从返回字节字符串__repr__
,而是返回Unicode字符串。
def __repr__(self):
return unicode(self) + self.units.decode('utf-8')
如果self.units
已经是Unicode字符串:
def __repr__(self):
return unicode(self) + self.units
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句