【问题标题】:Decode a string: Python解码字符串:Python
【发布时间】:2017-04-26 10:15:03
【问题描述】:

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

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

但它不起作用

【问题讨论】:

  • 我不确定这个问题与您之前的问题stackoverflow.com/questions/43629059/encoding-in-tuple-python 有何显着不同。此外,您不应该使用 Python 字符串格式来生成查询,您应该使用参数化查询,这本身可能会解决您的问题。
  • 是的,但我该怎么做呢?我不知道我的元组(数据)中的数字值
  • 用python2把# -*- coding: utf-8 -*-放到你的第一行。

标签: python utf-8 decode encode


【解决方案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))

【讨论】:

  • 感谢您的帮助和解释。我使用的是 psycopg2,所以参数化查询有点不同,但它真的对我有帮助!
  • @FrancoisBock 不客气,是%s 而不是??无论哪种方式,都不要使用字符串格式,这会让你对 SQL 注入持开放态度。
  • 是的,就是这样“'%s'”
猜你喜欢
  • 2011-10-18
  • 2017-11-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-26
  • 2016-12-27
  • 2011-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多