V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
mystar
V2EX  ›  Python

python3 数据结构中字节转字符串问题

  •  
  •   mystar · 2018-07-26 18:52:48 +08:00 · 1869 次点击
    这是一个创建于 2099 天前的主题,其中的信息可能已经有所发展或是发生改变。

    求问大佬,{b'status': b'Starting', b'CreateTime': b'1days', b'FinishedTime': b'2days'} 怎么才能将上面的字典中字节高效的转换成字符串

    {'status': 'Starting', 'CreateTime': '1days', 'FinishedTime': '2days'}

    5 条回复    2018-07-27 10:58:24 +08:00
    kunluanbudang
        1
    kunluanbudang  
       2018-07-26 18:58:23 +08:00
    ```
    In [1]: d1 = {b'status': b'Starting', b'CreateTime': b'1days', b'FinishedTime': b'2days'}

    In [2]: d1
    Out[2]: {b'status': b'Starting', b'CreateTime': b'1days', b'FinishedTime': b'2days'}

    In [3]: d2 = {k.decode('utf-8'): v.decode('utf-8') for k, v in d1.items()}

    In [4]: d2
    Out[4]: {'status': 'Starting', 'CreateTime': '1days', 'FinishedTime': '2days'}

    In [5]:
    ```

    like this?
    mystar
        2
    mystar  
    OP
       2018-07-26 19:16:51 +08:00
    @kunluanbudang 实在不行只能这样了,难道 python3 没有相关的 API 吗。。。
    compiler
        3
    compiler  
       2018-07-26 23:19:03 +08:00
    别去特意追求 Pythonic
    zhzer
        4
    zhzer  
       2018-07-27 08:50:11 +08:00
    高效?写 c 吧
    SoulMelody
        5
    SoulMelody  
       2018-07-27 10:58:24 +08:00
    import simplejson as json
    json.loads(json.dumps({b'status': b'Starting', b'CreateTime': b'1days', b'FinishedTime': b'2days'}))
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2829 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 00:22 · PVG 08:22 · LAX 17:22 · JFK 20:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.