Skip to main content
 首页 » 编程设计

Python3 字符串转换问题

2025年05月04日39zhoujg

我有一个函数:

def push(push): 
   ser.write(push + '\r') 
   pull = ser.read(11)   
   return pull 

我这样调用它:

out = push("ka " + dp_id + " ff") 

事实证明它与 python2 一起工作得很好但是当我使用 python 3 时我得到错误:

unicode strings are not supported, please encode to bytes: 'ka 01 ff\r'

现在如果我这样做:

out = push(b"ka " + display_id + " ff") 

我得到错误:

can't concat bytes to str

我很困惑。有什么帮助?

请您参考如下方法:

问题与push本身无关。你写:

b"ka " + display_id + " ff" 
# ^bytes ^string      ^string 

(b 前缀表示您实际上写了一个字节序列)。

这样就不行了。您可以使用 .encode() 将字符串编码 为字节数组,并在最后一个字符串上使用 b 前缀。所以:

b"ka " + display_id<b>.encode()</b> + <b>b</b>" ff" 
# ^bytes <b>^bytes</b>                <b>^bytes</b>