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

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

提交回复
热议问题