简体   繁体   English

Python - 字符串转换为列表

[英]Python - String conversion to list

I have a string field : "[Paris, Marseille, Pays-Bas]" .我有一个字符串字段: "[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 .如果我的输入数据是int类型,我可以使用ast.literal_eval() 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 .它将找到至少包含-AZaz

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 :只需使用切片和str.split

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

Or str.strip with str.split :str.stripstr.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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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