Python格式化字符串转义

时间:2013-10-27 10:36:00

标签: python string python-3.x formatting escaping

我正在尝试使用python中的格式创建查询,我无法弄清楚我如何能够为数据转义二进制输入。它返回如下内容:

  

INSERT INTO pythonUDPPacketDestinationSourceProtocolVersion,{{1 }},Header_LengthTTLProtoco l_UDPTargetSource_PortDestination_Port)VALUES(NULL,'00:0C:29: B2:14:0C','192.168.178.50','8','4','20','128','17','192.168.178.24','52371','8888','29227' ,'b'Data \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00'');)

如何在python中使用格式化正确地转义二进制字符串值?

Length

2 个答案:

答案 0 :(得分:7)

以防有人搜索此主题并被带到这里

这就是你为“格式”逃脱的方法:

>>> "{{}}{}".format(10)
'{}10'

因此,{{}}已转义并缩减为{}

答案 1 :(得分:2)

不要对SQL查询使用格式。使用SQL参数代替

您的数据库适配器随后将为您提供转义 ,前提是它可以处理二进制数据。

如何格式化SQL参数取决于所使用的数据库; sqlite3使用?占位符:

query = ("INSERT INTO `python`.`UDP` (`Packet`, `Destination`, `Source`, `Protocol`, "
         "`Version`, `Header_Length`, `TTL`, `Protocol_UDP`, `Target`, `Source_Port`, "
         "`Destination_Port`, `Length`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?))")

并且您将值列表作为cursor.execute()方法的第二个参数传递:

cursor.execute(query,
    (destination, source, protocol, version, header_length, ttl, protocolEGP, target, source_port, destination_port, length, data))

您需要在数据库适配器文档中验证支持style of SQL parameters的内容(?%s:1:name中的一个或多个或%(name)s)以及它如何处理二进制值。

如果根本不处理二进制值,则需要将该二进制值解码为unicode值;或许使用base64编码,或者从Latin-1解码以获得一对一的Unicode代码点转换。