解码字符串:Python

2024-05-29 02:15:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我用一个元组构建了一个字符串,如下所示:

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))

但它不起作用


Tags: 字符串comfbtablemailindividualagent元组
1条回答
网友
1楼 · 发布于 2024-05-29 02:15:53

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

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))

相关问题 更多 >

    热门问题