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?
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.
Use list :
s = '1989, 1990' [x.strip() for x in s.split(',')]
Short and light.
In addition, it has been asked many times!
split:
split
myList = s.split(', ')
print s.replace(' ','').split(',')
, .
:
>>> 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.
\s*,\s*
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)