string to list conversion in python

后端 未结 6 2049
借酒劲吻你
借酒劲吻你 2021-01-13 05:25

I have a string.

s = \'1989, 1990\'

I want to convert that to list using python & i want output as,

s = [\'1989\', \'19         


        
相关标签:
6条回答
  • 2021-01-13 05:45

    Use list comprehensions:

    s = '1989, 1990'
    [x.strip() for x in s.split(',')]
    

    Short and easy.

    Additionally, this has been asked many times!

    0 讨论(0)
  • 2021-01-13 05:50

    Call the split function:

    myList = s.split(', ')
    
    0 讨论(0)
  • 2021-01-13 05:54

    Use the split method:

    >>> '1989, 1990'.split(', ')
    ['1989', '1990']
    

    But you might want to:

    1. remove spaces using replace

    2. split by ','

    As such:

    >>> '1989, 1990,1991'.replace(' ', '').split(',')
    ['1989', '1990', '1991']
    

    This will work better if your string comes from user input, as the user may forget to hit space after a comma.

    0 讨论(0)
  • 2021-01-13 05:55

    i created generic method for this :

    def convertToList(v):
        '''
        @return: input is converted to a list if needed
        '''
        if type(v) is list:
            return v
        elif v == None:
            return []
        else:
            return [v]
    

    Maybe it is useful for your project.

    converToList(s)
    
    0 讨论(0)
  • 2021-01-13 06:02
    print s.replace(' ','').split(',')
    

    First removes spaces, then splits by comma.

    0 讨论(0)
  • 2021-01-13 06:02

    Or you can use regular expressions:

    >>> import re
    >>> re.split(r"\s*,\s*", "1999,2000, 1999 ,1998 , 2001")
    ['1999', '2000', '1999', '1998', '2001']
    

    The expression \s*,\s* matches zero or more whitespace characters, a comma and zero or more whitespace characters again.

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