0
私はPython 2でユニコードエラーが混乱していることを知っていますが、私が理解していないのは、str.format
がそうでなければ動作している状況にそれらを導入している理由です。 str.format
が、これは問題である一例に過ぎないと思われstr.formatを使用してユニコードエラーを作成するのはなぜですか?
>>> s = u'\xef'
>>> print s
ï
>>> print "%s" % s
ï
>>> print '' + s
ï
>>> print '{}'.format(s)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
print '{}'.format(s)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)
:私は私にこれを得たいくつかのUnicode文字とのトラブルを抱えて、IDLEをテストしていました。私はを推測しています何らかの理由で関数がasciiの適切な文字列を渡すだけという悪い仮定をしていますが、結果が不安定であるためにこれをどのように処理できるかを知りたいと思います。
これは、実際の文字またはコードを使用するかどうかにかかわらず、ユニコード文字列の場合にのみ発生します。細かいプレーンな文字列作品として両方の選択肢:
>>> s = 'ï'
>>> print '{}'.format(s)
ï
>>> s = '\xef'
>>> print '{}'.format(s)
ï
>>> s = u'ï'
>>> print '{}'.format(s)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print '{}'.format(s)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)
「悪い仮定」ではありません。それは歴史です。良いUnicodeサポートが導入される前の文字列の型とメソッドを使用すると、Unicodeのサポートが悪くなるか、まったくサポートされません。優れたUnicodeサポートが必要な場合は、Python 3を使用するか、Python 2でUnicode型を常に使用するように十分注意してください。 –