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?

asked Mar 28, 2012 at 10:19
1

6 Answers 6

8

Use list comprehensions:

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

Short and easy.

Additionally, this has been asked many times!

answered Mar 28, 2012 at 10:25
Sign up to request clarification or add additional context in comments.

1 Comment

This is a much better answer - replacing all spaces could affect the data, stripping the split items is a much better idea.
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.

answered Mar 28, 2012 at 10:21

2 Comments

"This will work better if your string comes from user input, as the user may forget to hit space after a comma." thats helpful.
Thank you for your feedback, please don't forget to close the question when you are done. This will save time from others who are reading unanswered questions to find someone with an unsolved issue to help
4

Call the split function:

myList = s.split(', ')
answered Mar 28, 2012 at 10:21

Comments

2
print s.replace(' ','').split(',')

First removes spaces, then splits by comma.

answered Mar 28, 2012 at 10:23

Comments

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.

answered Mar 28, 2012 at 10:33

Comments

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)
answered Mar 28, 2012 at 10:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.