5

I have a string.

s = '1989, 1990'

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

s = ['1989', '1990']

Is there any fastest one liner way for the same?

self
  • 2,634
  • 3
  • 16
  • 15
  • possible duplicate of [How do I split a string into a list Python?](http://stackoverflow.com/questions/88613/how-do-i-split-a-string-into-a-list-python) – mechanical_meat Mar 28 '12 at 15:05

6 Answers6

8

Use list comprehensions:

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

Short and easy.

Additionally, this has been asked many times!

Community
  • 1
  • 1
hochl
  • 12,524
  • 10
  • 53
  • 87
  • 1
    This is a much better answer - replacing all spaces could affect the data, stripping the split items is a much better idea. – Gareth Latty Mar 28 '12 at 10:45
4

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.

jpic
  • 32,891
  • 5
  • 112
  • 113
  • 1
    "This will work better if your string comes from user input, as the user may forget to hit space after a comma." thats helpful. – self Mar 28 '12 at 10:28
  • Thank you for your feedback, please don't forget to [close the question](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) when you are done. This will save time from others who are reading unanswered questions to find someone with an unsolved issue to help – jpic Mar 28 '12 at 10:29
4

Call the split function:

myList = s.split(', ')
MByD
  • 135,866
  • 28
  • 264
  • 277
2
print s.replace(' ','').split(',')

First removes spaces, then splits by comma.

jamylak
  • 128,818
  • 30
  • 231
  • 230
1

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.

codeape
  • 97,830
  • 24
  • 159
  • 188
1

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)
Selin
  • 616
  • 2
  • 9
  • 23