![](/img/trans.png)
[英]Byte array is a valid UTF8 encoded String in Java but not in Python
[英]unicode() vs. str.decode() for a utf8 encoded byte string (python 2.x)
有沒有理由更喜歡unicode(somestring, 'utf8')
而不是somestring.decode('utf8')
?
我唯一的想法是.decode()
是一個綁定方法,所以python可以更有效地解決它,但如果我錯了,請糾正我。
它很容易進行基准測試:
>>> from timeit import Timer
>>> ts = Timer("s.decode('utf-8')", "s = 'ééé'")
>>> ts.timeit()
8.9185450077056885
>>> tu = Timer("unicode(s, 'utf-8')", "s = 'ééé'")
>>> tu.timeit()
2.7656929492950439
>>>
顯然, unicode()
更快。
FWIW,我不知道你在哪里得到的方法會更快 - 這恰恰相反。
我更喜歡'something'.decode(...)
因為在Python 3.0中unicode
類型不再存在,而text = b'binarydata'.decode(encoding)
仍然有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.