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

后端 未结 14 581
予麋鹿
予麋鹿 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:42

    Using functional Python:

    text=filter(lambda x:x!=',',map(str,text))
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2020-11-28 03:52
    m = '[[1,2,3],[4,5,6],[7,8,9]]'
    
    m= eval(m.split()[0])
    
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    
    0 讨论(0)
  • 2020-11-28 03:55

    The following Python code will turn your string into a list of strings:

    import ast
    teststr = "['aaa','bbb','ccc']"
    testarray = ast.literal_eval(teststr)
    
    0 讨论(0)
  • 2020-11-28 03:58

    Just to add on to the existing answers: hopefully, you'll encounter something more like this in the future:

    >>> word = 'abc'
    >>> L = list(word)
    >>> L
    ['a', 'b', 'c']
    >>> ''.join(L)
    'abc'
    

    But what you're dealing with right now, go with @Cameron's answer.

    >>> word = 'a,b,c'
    >>> L = word.split(',')
    >>> L
    ['a', 'b', 'c']
    >>> ','.join(L)
    'a,b,c'
    
    0 讨论(0)
  • 2020-11-28 03:59

    I don't think you need to

    In python you seldom need to convert a string to a list, because strings and lists are very similar

    Changing the type

    If you really have a string which should be a character array, do this:

    In [1]: x = "foobar"
    In [2]: list(x)
    Out[2]: ['f', 'o', 'o', 'b', 'a', 'r']
    

    Not changing the type

    Note that Strings are very much like lists in python

    Strings have accessors, like lists

    In [3]: x[0]
    Out[3]: 'f'
    

    Strings are iterable, like lists

    In [4]: for i in range(len(x)):
    ...:     print x[i]
    ...:     
    f
    o
    o
    b
    a
    r
    

    TLDR

    Strings are lists. Almost.

    0 讨论(0)
提交回复
热议问题