나는 그것에 몇 가지 비 ASCIIUTF-8 인코딩 된 데이터와 문자열 변수를 작성하여 시작합니다왜 unicode()는 인코딩이없는 객체 만 str()을 사용합니까?
>>> text = 'á'
>>> text
'\xc3\xa1'
>>> text.decode('utf-8')
u'\xe1'
는 ... 거기에 unicode()
오류가 발생합니다
>>> unicode(text)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)
사용. 그러나 인코딩을 알면 두 번째 매개 변수로 사용할 수 있습니다.
나는 __str__()
방법이 텍스트 반환하는 클래스가 이제 경우 : 지금까지
>>> unicode(r)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)
: 그것은 위의 unicode(text)
과 같은 오류가 발생하기 때문에,
>>> class ReturnsEncoded(object):
... def __str__(self):
... return text
...
>>> r = ReturnsEncoded()
>>> str(r)
'\xc3\xa1'
unicode(r)
그것에 str()
를 사용하는 것을 모든 것이 계획대로!
그러나 이제까지 기대 아무도 같은
,unicode(r, 'utf-8')
는 시도조차하지 않습니다
>>> unicode(r, 'utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, ReturnsEncoded found
이유는 무엇입니까? 왜이 모순 된 행동? 그게 버그 야? 의도 된거야? 매우 어색함.
나는 내가 나 자신을 분명히하지 않았을 것이라고 생각한다. 나는 그것을 안다. 내 말은 유니 코드 (r)가 유니 코드 (r, 'utf-8')와 다른 동작을하는 이유를 아는 것입니다. ??? – nosklo
'utf-8'을 전달하지 않으면 ascii로 디코딩하려고하기 때문에 동작이 이상합니다. 하지만 'utf-8'을 통과하면 다른 오류가 발생합니다 ... – nosklo