Python网络编程_str<-->bytes转换
2016-08-07 12:04
806 查看
在Python网络编程中,会需要用到str与bytes的转化。这里简单介绍一下:
在Python IDLE中的效果是这样的:
再举个拙略的栗子:
实上我也是个初学者,只是借鉴别人的东西,不过学到手就是我的了。
戳这里
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 socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #生成socket对象 #host = socket.gethostname() host = '127.0.0.1' port = 1234 s.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()
实上我也是个初学者,只是借鉴别人的东西,不过学到手就是我的了。
戳这里
相关文章推荐
- 【Python基础】--Pickle/函数默认参数/函数的参数*args/Bytes<=>str/32-64bit/bytes对象
- Python基础<十二:网络编程>
- Python之Headers value 1 must be of type str or bytes, not <class 'int'>错误的解决
- <<Python基础教程>>学习笔记 | 第14章 | 网络编程
- <PY><core python programming笔记>C17 网络客户端编程
- Python 数列中的数的类型转换(Str<—>Int)
- <PY><core python programming笔记>C16 网络编程
- <<Python基础教程>>学习笔记 | 第14章 | 网络编程
- python3字符串编码总结str(unicode)<-->bytes
- <<Python编程实践>>之WhileBreakContinue
- head first c<11>初探网络编程下
- Python3中bytes和HexStr之间的转换
- <PY><core python programming笔记>C19 图形用户界面编程
- head first c<11>初探网络编程上
- <PY><core python programming笔记>C11 函数和函数式编程
- Java基础<十四>_网络编程
- <<C++网络编程 卷1 运用ACE和模式消除复杂性>>
- python3-网络编程-TypeError: send() argument 1 must be bytes or buffer, not str异常
- JAVA基础学习--网络编程<二>
- 我也写书评1---<[网络游戏服务器编程].(韩)全洪)>