解决TypeError: can only concatenate str (not “bytes”) to str
错误提示:
pic_content = pic_content+f.read()
TypeError: can only concatenate str (not “bytes”) to str
首先来看代码:
text_content = '''HTTP/1.x 200 OK Content-Type: text/html <head> <title>WOW</title> </head> <html> <p>Wow, Python Server</p> <IMG src="test.jpg"/> </html> ''' f = open('test.jpg', 'rb') pic_content = ''' HTTP/1.x 200 OK Content-Type: image/jpg ''' pic_content = pic_content+f.read()
rb:也即 binary mode,read()操作返回的是bytes
但是pic_content是 str类型的,所以这时候可以通过在pic_content字符串前加 b,把字符串类型转换成bytes 类型。
错误解决。
错误提示:
method = request.split(’ ')[0]
TypeError: a bytes-like object is required, not ‘str’
s.listen(3) conn, addr = s.accept() request = conn.recv(1024) method = request.split(' ')[0] src = request.split(' ')[1]
由代码块:recv 函数的返回值是 bytes 类型。
request是个bytes类型,但是split是对str进行操作的,所以此时要把bytes类型转换成str。也就是要对request 进行 decode操作:
request.decode()
修改两行代码 错误解决。
method = request.decode().split(' ')[0] src = request.decode().split(' ')[1]
u"我是含有中文字符组成的字符串。"
作用:后面字符串以 Unicode 格式 进行编码,一般用在中文字符串前面,防止因为源码储存格式问题,导致再次使用时出现乱码。
r"\n\n\n\n” # 表示一个普通生字符串 \n\n\n\n,而不表示换行了。
作用:去掉反斜杠的转译机制。
(特殊字符:即那些,反斜杠加上对应字母,表示对应的特殊含义的,比如最常见的”\n”表示换行,”\t”表示Tab等。 )
应用:常用于正则表达式,对应着re模块。
response = b'<h1>Hello World!</h1>' # b' ' 表示这是一个 bytes 对象
作用:b" "前缀表示:后面字符串是bytes 类型。
用处:网络编程中,服务器和浏览器只认bytes 类型数据。
如:send 函数的参数和 recv 函数的返回值都是 bytes 类型
在 Python3 中,bytes 和 str 的互相转换方式:
str→bytes:encode()方法。str通过encode()方法可以转换为bytes。
bytes→str: decode()方法。bytes通过decode()方法可以转换为str。
import time t0 = time.time() time.sleep(1) name = 'processing' #以 f开头表示在字符串内支持大括号内的python 表达式 print(f'{name} done in {time.time() - t0:.2f} s')
输出:
processing done in 1.00 s