推荐学习书目
› 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
scriptkid
V2EX  ›  Python

python 字符串形式的列表转列表

  •  2
     
  •   scriptkid · Dec 27, 2016 · 14197 views
    This topic created in 3620 days ago, the information mentioned may be changed or developed.

    RT, 假设有列表 a = [1, 2, 3, 4],那么可以用 str(a)转成字符串 '[1,2,3,4]'
    现在反过来想把字符串'[1,2,3,4]'转换成列表[1,2,3,4],有什么好的办法吗
    拒绝 eval ,毕竟危险函数,最好是类似 json 这样的

    8 replies  •  2016-12-27 16:26:22 +08:00
    billion
    billion
    Dec 27, 2016❤️1
    1
    ```
    >>> import json
    >>> a = '[1,2,2]'
    >>> b = json.loads(a)
    >>> b
    [1, 2, 2]
    ```
    Mistwave
    Mistwave
    Dec 27, 2016
    2
    >>> a = '[1,2,2]'
    >>> b = list(a)[1::2]
    >>> b
    ['1', '2', '2']

    如果有空格,可以先 split 然后 join 去空格(逃









    还是用 json 吧
    glasslion
    glasslion
    Dec 27, 2016❤️1
    3
    ast. literal_eval safe
    wyntergreg
    wyntergreg
    Dec 27, 2016
    4
    a = '[1, 2, 3, 4]'.strip('[').strip(']').split(',')
    Kisesy
    Kisesy
    Dec 27, 2016
    5
    eval 确实是危险函数,但是有几个人能写出让它危险的代码来,就你这个还怕危险。。。
    TKKONE
    TKKONE
    Dec 27, 2016
    6
    eval 虽然 evil ,但是只是将字符串转为 list 的话有多危险??
    hugo775128583
    hugo775128583
    Dec 27, 2016 via Android
    7
    @glasslion 正解
    scriptkid
    scriptkid
    OP
    Dec 27, 2016
    8
    @Kisesy
    @tumbzzc
    这里只是举个例子说明想要实现的是将传入字符串转为列表
    但程序并不会总是照着我们的想法来
    想象下如果传入的字符串是 “__import__('os').system('xxx')” 是什么后果
    最后还是很感谢回答
    @glasslion 给出了很好的答案
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2373 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 13:11 · PVG 21:11 · LAX 05:11 · JFK 08:11
    ♥ Do have faith in what you're doing.