2014-02-17 57 views
-1

我想從Sqlite進行查詢幷包含\ n,我期望python將其轉換爲換行符,但它不會。而且我也在數據庫中將\ n更改爲\ n,但仍然無法轉換。爲什麼Python在從Sqlite查詢時不會將 n轉換爲換行符?

cursor.execute('''SELECT test FROM table_name ''') 
for row in cursor: 
     self.ui.textEdit.append(row[0]) 
     # or 
     print row[0] 

我也試過unicode(row[0])並沒有工作。我很驚訝,在網絡上沒有一個簡單的解決方案。

+0

如果它是一個文字'\ n',它不會。 –

+0

@jayanth ok,但即使它不適用於\\ n – jesy2013

回答

0

SQLite和Python都沒有轉換字符串中的字符(\在源代碼中寫入的Python字符串中的轉義除外)。 如果你正確處理換行符,換行符正確工作:

>>> import sqlite3 
>>> db = sqlite3.connect(':memory:') 
>>> c = db.cursor() 
>>> c.execute('create table t(x)') 
>>> c.execute("insert into t values ('x\ny')") 
>>> c.execute("insert into t values ('x\\ny')") 
>>> c.execute("select * from t") 
>>> for row in c: 
... print row[0] 
... 
x 
y 
x\ny