I have a string.
s = \'1989, 1990\'
I want to convert that to list using python & i want output as,
s = [\'1989\', \'19
Use list comprehensions:
s = '1989, 1990'
[x.strip() for x in s.split(',')]
Short and easy.
Additionally, this has been asked many times!
Call the split
function:
myList = s.split(', ')
Use the split method:
>>> '1989, 1990'.split(', ')
['1989', '1990']
But you might want to:
remove spaces using replace
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.
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)
print s.replace(' ','').split(',')
First removes spaces, then splits by comma.
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.