我使用來讀取我的Python代碼的參數。其中一個輸入是可包含Unicode字符的文件標題[title
]。我一直在使用22少女時代22
作爲測試字符串。Python的Unicode編碼
我需要輸入title
的值寫入文件,但是當我嘗試將字符串轉換爲UTF-8
它總是拋出一個錯誤:
UnicodeDecodeError: 'ascii' codec can't decode byte 0x8f in position 2: ordinal not in range(128)
我一直環顧四周,看到我需要我的字符串將以u"foo"
的形式在其上調用.encode()
。
當我在我的輸入運行type()
從我看到:
<type 'str'>
我希望得到的響應:
<type 'unicode'>
我怎樣才能得到它在正確的形式?
理念:
修改採取一個str
,但其存儲爲Unicode字符串u"foo"
:
parser.add_argument(u'title', metavar='T', type=unicode, help='this will be unicode encoded.')
這種做法是行不通的。思考?
編輯1:
一些示例代碼,其中title
是22少女時代22
:
inputs = vars(parser.parse_args())
title = inputs["title"]
print type(title)
print type(u'foo')
title = title.encode('utf8') # This line throws the error
print title
輸入數據是什麼編碼? –
@MarkTolonen好的,我會編輯我的帖子。 – Morrowind789