【问题标题】:Python formatting string escapePython格式化字符串转义
【发布时间】:2013-10-27 10:35:59
【问题描述】:

我正在尝试在 python 中创建一个带有格式的查询,我不知道如何对数据的二进制输入进行字符串转义。它返回如下内容:

插入python.UDP (Packet, Destination, Source, Protocol, Version, Header_Length, TTL, Target, @98765433@@, @98765433@@, 987654332@, Destination_Port, Length) 值 (NULL, '00:0C:29:B2:14:0C', '192.168.178.50', '8', '4', '20', '128' , '17', '192.168.178.24', '52371', '8888', '29227', 'b'数据\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ x00\x00\x00'');)

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

def setopUDP(destination, source, protocol, version, header_length, ttl, protocolEGP, target, source_port, destination_port, length, data):
query = ("INSERT INTO `python`.`UDP` (`Packet`, `Destination`, `Source`, `Protocol`, "
         "`Version`, `Header_Length`, `TTL`, `Protocol_UDP`, `Target`, `Source_Port`, "
         "`Destination_Port`, `Length`) VALUES (NULL, '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}');)"
         .format(destination, source, protocol, version, header_length, ttl, protocolEGP, target, source_port, destination_port, length, data))


setopCON(query)  

【问题讨论】:

  • 你用的是什么数据库适配器?

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


【解决方案1】:

以防万一有人搜索了这个主题并被引导到这里

这就是您对“格式”进行转义的方式:

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

所以,{{}} 被转义并简化为 {}

【讨论】:

    【解决方案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 中的一个或多个)以及它如何处理二进制文件价值观。

    如果根本不处理二进制值,则需要将该二进制值解码为 un​​icode 值;可能使用 base64 编码,或者从 Latin-1 解码以一对一地转换为 Unicode 代码点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-28
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      • 2019-03-14
      相关资源
      最近更新 更多