我正在尝试在 Python 中连接字符串和字节。这不起作用,但我认为如果我们可以摆脱b''并将字节对象视为字符串,它可能会起作用:
import binascii
s = 'hello world'
hex_code = binascii.hexlify(bytes(s, 'utf-8'))
print(hex_code) # b'68656c6c6f20776f726c64'
# this would work
print('68656c6c6f20776f726c64' + ' some other string')
# this fails
print(hex_code + ' some other string')
我的最终用例是完全不相关的东西。SQL Server 支持通过发出需要对元数据进行编码的“SET CONTEXT_INFO”命令来设置元数据。理想情况下,我想从我的应用程序中构建这个元数据。我的命令可能类似于:
import bin2ascii
def set_context(conn, context_info: str):
hex_string = binascii.hexlify(bytes(context_info, 'utf-8'))
conn.execute('SET CONTEXT_INFO 0x' + hex_string)
这当然行不通,因为我想不出一种连接字符串和字节的方法。