2015-05-15 80 views
0

我試圖打印下面的unicode字符串,但我收到了UnicodeDecodeError: 'ascii' codec can't decode byte錯誤。你能幫助形成這個查詢,以便它可以正確打印unicode字符串嗎?Python 2.7.6 + unicode_literals - UnicodeDecodeError:'ascii'編解碼器無法解碼字節

>>> from __future__ import unicode_literals 
>>> ts='now' 
>>> free_form_request='[EXID(이엑스아이디)] 위아래 (UP&DOWN) MV' 
>>> nick='me' 

>>> print('{ts}: free form request {free_form_request} requested from {nick}'.format(ts=ts,free_form_request=free_form_request.encode('utf-8'),nick=nick)) 

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xec in position 6: ordinal not in range(128) 

非常感謝您提前!

+0

刪除編碼 –

+0

嘗試[忽略錯誤](https://docs.python.org/2/library/stdtypes.html#str.encode):'free_form_request.encode('utf-8',errors = 'ignore')' –

+0

@PeterWood這將不起作用,當字符串在編碼後解碼時會發生問題。請注意,由於unicode_literals導入,該字符串已經是unicode。 –

回答

3

這裏就是當你構建這個字符串發生什麼:

'{ts}: free form request {free_form_request} requested from {nick}'.format(ts=ts,free_form_request=free_form_request.encode('utf-8'),nick=nick) 
  1. free_form_requestencode -d到使用utf-8作爲編碼一個字節串。這是可行的,因爲utf-8可以代表[EXID(이엑스아이디)] 위아래 (UP&DOWN) MV
  2. 但是,格式字符串('{ts}: free form request {free_form_request} requested from {nick}')是unicode字符串(因爲導入的from __future__ import unicode_literals)。
  3. 不能使用字節串作爲格式參數的unicode字符串,所以Python試圖decode在1中創建的字節串創建unicode字符串(這將是作爲一個格式參數無效)。
  4. Python嘗試decode -ing使用默認編碼,即ascii,並且失敗,因爲字節字符串是一個utf-8字節字符串,其中包含的字節值在ascii中沒有意義。
  5. Python拋出一個UnicodeDecodeError

注意的是,雖然該代碼顯然是做的東西在這裏,這實際上不是扔在Python 3的異常,這反而會替代字節字符串的repr(在repr是一個unicode字符串)。


要解決您的問題,只需將unicode字符串傳遞給format即可。

也就是說,不執行步驟1,您編碼free_form_request作爲一個字節的字符串:通過去除.encode(...)保持它作爲一個Unicode字符串:

'{ts}: free form request {free_form_request} requested from {nick}'.format(
    ts=ts, 
    free_form_request=free_form_request, 
    nick=nick) 

注帕德里克·坎寧安的答案評論以及。

+0

我在較大的函數中有原始問題的代碼塊。原來我導入的東西重寫了打印函數,無法正確處理unicode字符串。不幸的是,我的解決方法是編碼('ascii',錯誤='忽略')並放棄unicode字符並處理。 –

+0

@PrestonConnors然後你應該編碼格式化的字符串,而不是格式參數。只需要:'print('...'。format(...)。編碼('utf-8'))' –

+0

儘管原始代碼不會在Python 3上引發異常,但Python 3並不隱式地將字節串解碼爲Unicode(步驟3),所以打印出來的是'repr字節串編碼。爲了正確的工作在Python 3上,'encode'仍然必須被移除。 –

相關問題