Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - String conversion to list

Tags:

python

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

like image 488
Clement Ros Avatar asked May 07 '26 18:05

Clement Ros


2 Answers

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 -, A-Z, and a-z.

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

string2 = " [  Paris, Marseille  , Pays-Bas  ] "
string3 = "   [ Paris  ,  Marseille  ,   Pays-Bas  ] "
like image 103
ghchoi Avatar answered May 11 '26 05:05

ghchoi


This splits it into a list of strings:

'[Paris, Marseille, Pays-Bas]'.strip('[]').split(', ')                                                                                                                               
# ['Paris', 'Marseille', 'Pays-Bas']
like image 39
oppressionslayer Avatar answered May 11 '26 05:05

oppressionslayer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!