2013-01-16 46 views
0

我有一個典型的utf-8編碼問題,但到目前爲止我還沒有能夠解決它。Python編碼問題(ascii> unicode)

class StatsTandE(webapp2.RequestHandler): 
    def get(self): 

    conn = rdbms.connect(instance=_INSTANCE_NAME, database='origami') 
    cursor = conn.cursor() 
    cursor.execute('SELECT ui.displayName, ui.title, ui.costCenter FROM views AS v') 
    results = [[str(row[0]), str(row[1]), str(row[2])] for row in cursor.fetchall()] 
    logging.info('results identified as %s', results) 

    template_file_name = 'templates/stats_results.html' 
    template_values = { 
     'results': results, 
    } 

    path = os.path.join(os.path.dirname(__file__), template_file_name) 
    self.response.out.write(template.render(path, template_values)) 
    conn.close() 

我看到的錯誤是:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 4: ordinal not in range(128) 

更改str(row[0])str(row[0]).encode('utf-8')沒有工作......

有什麼建議?

+0

你正在使用哪個版本的python?無論您使用的是Python 2.X還是Python 3,Unicode問題都以不同的方式解決。 –

+0

如果字符串將包含UTF-8字符,則應在Python 2中使用「unicode」數據類型。 – Borealid

+0

我們使用Python 2.7 。我將如何設置'unicode'數據類型? – koend

回答

1

嘗試將str(row[0])更改爲unicode(row[0])

更新:正如其他人所說:除非您需要,否則您甚至不應使用unicodestr。試試row[0], row[1], row[2]。當你需要顯示它時,可以這樣做:row[0].encode('utf8')

+0

工作正常!但是,如何將unicode再次轉換爲字符串,以便在頁面上很好地顯示?我會再解碼一次嗎? – koend