Python网络编程_str<-->bytes转换

来源:互联网 发布:小米算法工程师笔试 编辑:程序博客网 时间:2024/06/10 04:06

在Python网络编程中,会需要用到str与bytes的转化。这里简单介绍一下:

1    bytes object :  b = b"example"   2    str object   :  s = "example"    3    #str to bytes  4    bytes(s, encoding = "utf8")   5    #bytes to str  6    str(b, encoding = "utf-8")  7    #an alternative method   8    #str to bytes  9    str.encode(s)   10   #bytes to str   11   bytes.decode(b)

在Python IDLE中的效果是这样的:

>>> b = b"example">>> s = 'example'>>> bytes(s, encoding = "utf8")b'example'>>> str(b, encoding = "utf-8")'example'>>> str.encode(s)b'example'>>> bytes.decode(b)'example``>>> 

再举个拙略的栗子:

#filename: simple_server.py#服务器端import sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)   #生成socket对象#host = socket.gethostname()host = '127.0.0.1'port = 1234s.bind((host, port))    #绑定socket地址s.listen(10)    #开始监听while True:    c, addr = s.accept()    #接受一个连接    print("Get cnnection from", addr)    msg = input("Please tell me y    c.send(str.encode(msg))   #参数类型必须是bytes参数类型必须是bytes  c.close()

实上我也是个初学者,只是借鉴别人的东西,不过学到手就是我的了。
戳这里

0 0