는 파이썬의 string.format()
에 문제가 있으며 유니 코드 문자열을 전달하고있다. 이것은하지 logging.info()
통화, 테스트 코드 폭발 인쇄에 내 경우를 제외, this older question 유사하다. 같은 유니 코드 문자열 개체를 로깅 처리기에 전달하면 정상적으로 작동합니다.파이썬의 인 String.format() 및 유니 코드
이것은 string.format()
뿐만 아니라 이전 %
서식 동일하게 실패합니다. 문제가되는 문자열 객체인지 확인하고 터미널과의 상호 작용이 잘못 인쇄되지 않도록하기 위해 인쇄하기 전에 형식화 된 문자열을 변수에 할당 해 보았습니다.
def unicode_test():
byte_string = '\xc3\xb4'
unicode_string = unicode(byte_string, "utf-8")
print "unicode object type: {}".format(type(unicode_string))
output_string = "printed unicode object: {}".format(unicode_string)
print output_string
if __name__ == '__main__':
unicode_test()
문자열 개체가 ASCII로 간주됩니다.
% python -V
Python 2.7.2
% python ./unicodetest.py
unicode object type: <type 'unicode'>
Traceback (most recent call last):
File "./unicodetest.py", line 10, in <module>
unicode_test()
File "./unicodetest.py", line 6, in unicode_test
output_string = "printed unicode object: {}".format(unicode_string)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf4' in position 0: ordinal not in range(128)
유니 코드가 어떤 변화를하지 않는 output_string
캐스팅하려고합니다.
output_string = U "인쇄 된 유니 코드 개체 : {}". 형식 (UNICODE_STRING)
내가 여기서 뭔가를 놓치고 있습니까? 문자열 객체에 대한 문서는이 객체를 사용하려고 시도 할 때 제대로 작동한다는 것을 분명히합니다.
파이썬 3에서 수정 된 그러나'에 붙이는 '인쇄 유니 코드 object'는 u' 나 (파이썬 2.6.5 및 2.7)에 적용됩니다. 위에 열거 된 오류와 동일한 오류가 발생 했습니까? – RocketDonkey
대기 ... 이미 인코딩 된 유니 코드 스트림을 나타내는 것으로 가정되는 유니 코드 바이트 스트림을 인코딩하고 있습니까? 어떤 문자가' '\ xc3 \ xb4' '에 인쇄되어야합니까? :'ô' 또는'Ã''? –
ô해야합니다. 인코딩 예제는 로깅 모듈에 대한 참조 된 이전 게시물에서 거의 그대로 복사되었습니다. – mpounsett