解码一个字符串:Python

时间:2017-04-26 10:15:03

标签: python utf-8 decode encode

我用这样的元组构建了一个字符串:

t = tuple(data)
querysring="INSERT INTO %s VALUES %s "%(table,t)

当我打印字符串时,结果为:

INSERT INTO AGENT VALUES ('Bock', 'Fran\\xc3\\xa7ois Bock', 'Individual', 'fb****@mail.com')

但我想要这样的事情:

 INSERT INTO AGENT VALUES ('Bock', 'François Bock', 'Individual', 'fb****@mail.com')

可以解码字符串吗? 我使用Python2.x但我可以使用Python3.x

我试试这个:

querysring=u"INSERT INTO %s VALUES %s "%(table,t)
print(ftfy.fix_text(querysring))

但它不能正常工作

1 个答案:

答案 0 :(得分:1)

我认为您的问题很肤浅,与print如何以不同方式显示列表和列表项有关。即使列表中的ascii中正确编码,列表的打印输出也在utf-8。首先,使用chardet库:

from chardet.universaldetector import UniversalDetector

a = ['Bock', 'François Bock']

detector = UniversalDetector()
detector.feed(str(a))
detector.close()

print "Encoding for the str(list): ", detector.result

detector = UniversalDetector()
detector.feed(a[1])
detector.close()

print "Encoding for list[1]:       ", detector.result

print "The whole list:             ", a
print "Item in list:               ", a[1]

除了令人反感的打印输出外,还可以使用参数化查询以正确的编码写入数据库。以下代码的最后一部分写入文件以确认数据编码被保留:

import sqlite3

conn = sqlite3.connect(":memory:")
conn.text_factory = str
c = conn.cursor()

c.execute("CREATE TABLE IF NOT EXISTS testing(test1 TEXT, test2 TEXT)")
conn.commit()

my_tuple = 'Bock', 'François Bock'
table = 'testing'

placeholders = ', '.join('?' for item in my_tuple)
query = "INSERT INTO {} VALUES ({})".format(table, placeholders)

c.execute(query, my_tuple)

c.execute("SELECT * FROM testing")
all_data = c.fetchone()

# Check the printouts
print all_data
print all_data[1]

# For good measure, write them to a file
with open('check_output.txt', 'w') as outfile:
    outfile.write(', '.join(item for item in all_data))