环境: python3
假如我创建这样一个二进制的字节流
b = b'\xaa\xbb\xcc'
那么我怎样才能得到字符串
"aabbcc"
13 条回复 • 2020-08-04 14:33:47 +08:00
|
1
knightdf 2020 年 8 月 3 日
b.decode(xxx)
|
|
2
si 2020 年 8 月 3 日
你这个意思是要字符串转十六进制吗,那直接搜索就有了
|
|
3
CharAct3 2020 年 8 月 3 日 b.hex()
|
|
4
smallpython OP @CharAct3 感谢
|
|
5
smallpython OP @si 是十六进制转字符串吧, 用字符串的形式表现一个字节流的具体内容
|
|
6
hakono 2020 年 8 月 3 日
1 楼都直接给出正确答案了。。。。。
|
|
7
fasionchan 2020 年 8 月 3 日
1 楼说的就是答案,推荐看一些关于 bytes 对象、str 对象以及文本编码的材料:
文本编码: https://python.fasionchan.com/zh_CN/latest/practices/coding.html str 对象: https://mp.weixin.qq.com/s/E7z2yN8V9ac2pUTfgqDg9Q |
|
8
ytymf 2020 年 8 月 3 日
明明 3 楼才是正确答案,都不好好看看楼主问题。
|
|
9
imn1 2020 年 8 月 3 日
#3 才是正解,看需求不是类型转换
decode 得不到"aabbcc" |
|
10
wittyfans 2020 年 8 月 3 日 via iPhone
记的一点笔记,希望有所帮助:
# string to bytes, then to numbers s = '你好' list(bytes(s,encoding='utf8')) Output:[228, 189, 160, 229, 165, 189] # string to bytes then to string bytes(s,encoding='utf8').decode('utf8') Output:'你好' # list numbers to bytes then to string bytes([228, 189, 160, 229, 165, 189]).decode('utf8') Output:'你好' # str s = 'hello' # bytes b = b'hello' # ok s + s # error try: s + b except TypeError: print('发生错误') Output:发生错误 |
|
11
lolizeppelin 2020 年 8 月 4 日
你先说清楚要干嘛
内部直接 decode 网络传输直接 struct pack unpack ctype 就转 ctype 的对应的 |
|
12
smallpython OP @lolizeppelin 就是如题目所说呀, 三楼就是我要的答案, 他说之前我都不知道还有这个方法....
|
|
13
smallpython OP @wittyfans 谢谢你的答案, 但是你这个想表达的是先转换成数字, 然后再把数字转换成 16 进制字符串吗, 感觉绕了一圈
|
推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide