How to convert a string with comma-delimited items to a list in Python?

后端 未结 14 573
予麋鹿
予麋鹿 2020-11-28 03:09

How do you convert a string into a list?

Say the string is like text = \"a,b,c\". After the conversion, text == [\'a\', \'b\', \'c\'] and h

相关标签:
14条回答
  • 2020-11-28 04:07
    # to strip `,` and `.` from a string ->
    
    >>> 'a,b,c.'.translate(None, ',.')
    'abc'
    

    You should use the built-in translate method for strings.

    Type help('abc'.translate) at Python shell for more info.

    0 讨论(0)
  • 2020-11-28 04:09

    Like this:

    >>> text = 'a,b,c'
    >>> text = text.split(',')
    >>> text
    [ 'a', 'b', 'c' ]
    

    Alternatively, you can use eval() if you trust the string to be safe:

    >>> text = 'a,b,c'
    >>> text = eval('[' + text + ']')
    
    0 讨论(0)
提交回复
热议问题