Python error: can't concat str to bytes
如果用到了encode函数,要注意这个函数返回的是bytes 类型的变量,不可以和string类型的变量 直接合并,比如:
>>> 'I am '.encode('utf-8')+' alex '
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't concat str to bytes
需要再调用decode函数,把bytes类型转变为string类型
>>> 'I am '.encode('utf-8').decode()+' alex '
'I am alex '
注意:如果不调用decode,直接用str函数直接转换,会出现下面的结果:
英文:
>>> str('I am '.encode('utf-8'))+' alex '
"b'I am ' alex "
中文:
>>> str('我是 '.encode('utf-8'))+' alex '
"b'\\xe6\\x88\\x91\\xe6\\x98\\xaf ' alex "
所以正确的做法是调用decode函数:
>>> '我是 '.encode('utf-8').decode()+' alex '
'我是 alex '