简体   繁体   中英

string to list conversion in python

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?

Use list comprehensions :

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

Short and easy.

Additionally, this has been asked many times!

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.

调用split功能:

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

首先删除空格,然后用逗号分割。

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM