あなたとUTF-8エンコードされた文字列を混在させるときに私はUnicode文字列での作業持っていた問題の主な原因は次のようなエラーで
foo = "barré"
結果次のようなそうでないラインユニコードのもの。
たとえば、次のスクリプトを考えます。
two.py
# encoding: utf-8
name = 'helló wörld from two'
one.py
# encoding: utf-8
from __future__ import unicode_literals
import two
name = 'helló wörld from one'
print name + two.name
python one.py
を実行の出力はこの例では
Traceback (most recent call last):
File "one.py", line 5, in <module>
print name + two.name
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128)
、two.name
は、UTF-8でエンコードされた文字列であります(unicodeではなく)unicode_literals
とをインポートしなかったためですはユニコード文字列です。両方を混在させると、Pythonはエンコードされた文字列をデコードし(ASCIIであると仮定して)、ユニコードに変換して失敗します。 print name + two.name.decode('utf-8')
を実行した場合は正常に機能します。
文字列をエンコードして後でミックスすると同じことが起こります。 は例えば、これは動作します:
# encoding: utf-8
html = '<html><body>helló wörld</body></html>'
if isinstance(html, unicode):
html = html.encode('utf-8')
print 'DEBUG: %s' % html
出力:
DEBUG: <html><body>helló wörld</body></html>
しかし、それはしないimport unicode_literals
を追加した後:
# encoding: utf-8
from __future__ import unicode_literals
html = '<html><body>helló wörld</body></html>'
if isinstance(html, unicode):
html = html.encode('utf-8')
print 'DEBUG: %s' % html
出力:
Traceback (most recent call last):
File "test.py", line 6, in <module>
print 'DEBUG: %s' % html
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 16: ordinal not in range(128)
を'DEBUG: %s'
はユニコード文字列であるため、pythonはhtml
をデコードしようとするため失敗します。印刷物を修正するには、print str('DEBUG: %s') % html
またはprint 'DEBUG: %s' % html.decode('utf-8')
のいずれかの方法があります。
これは、ユニコード文字列を使用する際の潜在的な問題点を理解するのに役立ちます。
私は 'str()'や 'encode()'の代わりに 'decode()'を使うことをお勧めします:Unicodeオブジェクトを使う頻度が高いほど、コードが明確になります。外部的に暗示されたエンコーディングを持つバイト配列ではなく、文字列を操作します。 – EOL
用語を修正してください。UTF-8でエンコードされた文字列とUnicodeの文字列を混在させた場合UTF-8とUnicodeでは2つの異なるエンコーディングがありません。 Unicodeは標準であり、UTF-8はそれが定義するエンコーディングの1つです。 – Kos
@Kos:私は彼がユニコード(結果としてデコードされた)*オブジェクト*とオブジェクト "*を組み合わせた" utf-8でエンコードされた文字列 "を意味すると思います。前者は 'str'型、後者は' unicode'型です。 – MestreLion