简体   繁体   中英

Python - String conversion to list

I have a string field : "[Paris, Marseille, Pays-Bas]" . I want to convert this string to a list of strings.

For now I have the following function :

def stringToList(string):
    string = string[1:len(string)-1]
    try:
        if len(string) != 0: 
            tempList = string.split(", ")
            newList = list(map(lambda x: str(x), tempList))
        else:
            newList = []
    except:
        newList = [-9999]

    return(newList)

I want to know if there is a simpler or a shorter method with the same results. I could use ast.literal_eval() if my input data were of type int . But in my case, it does not work.

Thank you

Worth to know:

import re

string = "[Paris, Marseille, Pays-Bas]"
founds = re.findall('[\-A-Za-z]+', string)

It will find all that consist at least one of of - , AZ , and az .

One pros is that it can work with less-neat strings like:

string2 = " [  Paris, Marseille  , Pays-Bas  ] "
string3 = "   [ Paris  ,  Marseille  ,   Pays-Bas  ] "

This splits it into a list of strings:

'[Paris, Marseille, Pays-Bas]'.strip('[]').split(', ')                                                                                                                               
# ['Paris', 'Marseille', 'Pays-Bas']

Just use slicing and str.split :

>>> s = '[Paris, Marseille, Pays-Bas]'
>>> s[1:-1].split(', ')
['Paris', 'Marseille', 'Pays-Bas']
>>> 

Or str.strip with str.split :

>>> s = '[Paris, Marseille, Pays-Bas]'
>>> s.strip('[]').split(', ')
['Paris', 'Marseille', 'Pays-Bas']
>>> 

try this :

s = "[Paris, Marseille, Pays-Bas]"

s = [i.replace('[','').replace(']','').replace(' ','') for i in 
s.split(',')]
print(s)

output:

['Paris', 'Marseille', 'Pays-Bas']

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