cannot use a string pattern on a bytes-like object(bytes与str互转)
生活随笔
收集整理的这篇文章主要介绍了
cannot use a string pattern on a bytes-like object(bytes与str互转)
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
python2转python3遇到的问题
看源码:
buff = proc.communicate() stritem = buff[0] str_list = re.split(r' +|\n', stritem)运行出现错误:
cannot use a string pattern on a bytes-like object
这是因为 stritem = buff[0] 得到的结果为bytes类型,而在python2中为str类型。
这里谈到一个转换问题:bytes与str的互转
从str到bytes:调用方法encode().
编码是把Unicode字符串以各种方式编码成为机器能读懂的ASCII字符串
从bytes到str:调用方法decode().
将源码改为:
buff = proc.communicate() stritem = buff[0].decode() str_list = re.split(r' +|\n', stritem)完成
总结
以上是生活随笔为你收集整理的cannot use a string pattern on a bytes-like object(bytes与str互转)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 工业控制系统ICS网络安全简析
- 下一篇: Twisted SSH