String to convert a list in python

I have a line.

s = '1989, 1990'

I want to convert this to a list using python, and I want output as,

s = ['1989', '1990']

Is there any fastest way for liner to do the same?

+5
source share
6 answers

Use the separation method :

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

But you may want to:

  • remove spaces with replace

  • split by ','

In this way:

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

This will work better if your line comes from user input, as the user may forget to run after the decimal point.

+4
source

Use list :

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

Short and light.

In addition, it has been asked many times!

+8

split:

myList = s.split(', ')
+4
print s.replace(' ','').split(',')

, .

+2

:

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

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

+1
source

I created a general 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]

Perhaps this is useful for your project.

converToList(s)
+1
source

All Articles