我只有一個元素的列表,它本身就是一個元素列表。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'是我打算單獨存儲所有名稱的列表。我的代碼似乎有什麼問題?
'名稱列表= nameStr的[1:-1] .split( ' 「」')'? – Hyperboreus
這個字符串從哪裏來的?這看起來很像一行CSV文件。 – DSM
我從我正在使用的文件中獲得該字符串。 –