Python:将字符串拆分为元素并将其添加到列表中

时间:2014-04-05 22:53:31

标签: python

我有一个只有一个元素的列表,它本身就是一个元素列表。

str = '"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA","SUSAN","MARGARET","DOROTHY","LISA","NANCY","KAREN","BETTY","HELEN","SANDRA","DONNA","CAROL"'

现在,我希望该字符串中的每个名称都包含在另一个列表中。为此,我理解我必须单独拆分每个名称,然后将它们附加到所需的列表中。这是我为此写的代码:

str = '"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA","SUSAN","MARGARET","DOROTHY","LISA","NANCY","KAREN","BETTY","HELEN","SANDRA","DONNA","CAROL"'
li = str.split()
c = li[0]
ip = []
start = c.find('"')
final = c.find('"', start+1)
def iter(start, final):
    e = c[start+1:final]
    ip.append(e)
nstart = c.find('"', final+1)
nfinal = c.find('"', nstart+1)
if(nstart == -1 or nfinal == -1):
    print ip
else:
    iter(nstart, nfinal)

但是,我没有得到任何输出。 'ip'是我打算单独存储所有名称的列表。我的代码似乎有什么问题?

3 个答案:

答案 0 :(得分:2)

首先,调用某些内容str是不好的,因为str是python中的内置函数。

其次,您可以使用以下方法执行此操作:

in_list_string = '"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA","SUSAN","MARGARET","DOROTHY","LISA","NANCY","KAREN","BETTY","HELEN","SANDRA","DONNA","CAROL"'
out_list= [element.strip('"') for element in in_list_string.split(',')]

答案 1 :(得分:2)

您的代码远比必要复杂得多。您可以使用评论,或执行:

foo = '"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA","SUSAN","MARGARET","DOROTHY","LISA","NANCY","KAREN","BETTY","HELEN","SANDRA","DONNA","CAROL"'
output = foo.replace('"','').split(",")

答案 2 :(得分:2)

the csv module用于csv数据:

>>> import csv
>>> from StringIO import StringIO
>>> dont_call_me_str='"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA","SUSAN","MARGARET","DOROTHY","LISA","NANCY","KAREN","BETTY","HELEN","SANDRA","DONNA","CAROL"'
>>> list(csv.reader(StringIO(dont_call_me_str)))
[['MARY', 'PATRICIA', 'LINDA', 'BARBARA', 'ELIZABETH', 'JENNIFER', 'MARIA', 'SUSAN', 'MARGARET', 'DOROTHY', 'LISA', 'NANCY', 'KAREN', 'BETTY', 'HELEN', 'SANDRA', 'DONNA', 'CAROL']]