[英]Handle UnicodeEncodeError in python2.7
我有以下代碼:
for index, row in df_out.iterrows():
yield {
'CustomerName': str(row['CustomerName'])
}
我得到了UnicodeEncodeError:
RuntimeError: UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 10: ordinal not in range(128)
如何處理該零件以避免該錯誤?
str(row['CustomerName'])
如果您可能在python2中處理非ASCII文本,則可以
str(some_text)
通常是個壞主意,因為如果some_text
包含非ASCII字符,則會收到UnicodeEncodeError
。 正確的代碼是
unicode(some_text)
因為unicode()
不會嘗試將文本編碼為ASCII。
但是鑒於此代碼
for index, row in df_out.iterrows():
yield {
'CustomerName': str(row['CustomerName'])
}
row['CustomerName']
很可能已經是一個unicode
對象,因此在其上調用unicode
將是多余的。 這可能會起作用:
for index, row in df_out.iterrows():
yield {
'CustomerName': row['CustomerName']
}
總結一下:刪除str
調用。 如果這樣不起作用,請嘗試將str
替換為unicode
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.