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

后端 未结 14 644
予麋鹿
予麋鹿 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 03:48

    If you actually want arrays:

    >>> from array import array
    >>> text = "a,b,c"
    >>> text = text.replace(',', '')
    >>> myarray = array('c', text)
    >>> myarray
    array('c', 'abc')
    >>> myarray[0]
    'a'
    >>> myarray[1]
    'b'
    

    If you do not need arrays, and only want to look by index at your characters, remember a string is an iterable, just like a list except the fact that it is immutable:

    >>> text = "a,b,c"
    >>> text = text.replace(',', '')
    >>> text[0]
    'a'
    

提交回复
热议问题