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

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

    split() is your friend here. I will cover a few aspects of split() that are not covered by other answers.

    • If no arguments are passed to split(), it would split the string based on whitespace characters (space, tab, and newline). Leading and trailing whitespace is ignored. Also, consecutive whitespaces are treated as a single delimiter.

    Example:

    >>> "   \t\t\none  two    three\t\t\tfour\nfive\n\n".split()
    ['one', 'two', 'three', 'four', 'five']
    
    • When a single character delimiter is passed, split() behaves quite differently from its default behavior. In this case, leading/trailing delimiters are not ignored, repeating delimiters are not "coalesced" into one either.

    Example:

    >>> ",,one,two,three,,\n four\tfive".split(',')
    ['', '', 'one', 'two', 'three', '', '\n four\tfive']
    

    So, if stripping of whitespaces is desired while splitting a string based on a non-whitespace delimiter, use this construct:

    words = [item.strip() for item in string.split(',')]
    
    • When a multi-character string is passed as the delimiter, it is taken as a single delimiter and not as a character class or a set of delimiters.

    Example:

    >>> "one,two,three,,four".split(',,')
    ['one,two,three', 'four']
    

    To coalesce multiple delimiters into one, you would need to use re.split(regex, string) approach. See the related posts below.


    Related

    • string.split() - Python documentation
    • re.split() - Python documentation
    • Split string based on regex
    • Split string based on a regular expression

提交回复
热议问题