這是瞭解Python字符串和列表的好方法。既然你最初有一個字符串,字符串有一個劃分方法,可以讓你基於傳遞給拆
my_list = string.split('=')
所以這個分裂的=您的字符串簽署部分拆分值將字符串分解被收集在一個名單
my_list = ['<node> user ', ' "bob" password ', '"123" </node> <node> user ', ' "john" password ', '"123" </node> <node> user ', ' "will" password ', '"1234" </node> <node> user ', ' "andrew" password ', '"12345" </node> <node> user ', ' "mike" password ', '"123456" </node>']
如果你仔細看,名字都包含在也有字的密碼列表中的項目,所以我們將使用該規律來獲得下一步
names = [] # this will hold the names after we find them
for item in my_list:
if 'password' not in item:
continue # if password is not in the item then we don't want to do anything so get the next item
name = item.strip().split(' ')[0] # get rid of the leading blank space (and trailing) then split on the blank space keep the first item in the resulting list
name = name.replace('"','') # I assume you want to get rid of the double quotes as they are not part of the name
names.append(name)
現在的名字是一個名字列表
['bob', 'john', 'will', 'andrew', 'mike']
*「你能請任何代碼來解決我的問題嗎?」* - 這是**不** **如何堆棧溢出的作品。 *寫一些自己*,並學習[問]。 *「如何做......但對我的例子」*是整個學習**的全部觀點,如果你不能採用一般的解決方案來滿足你的具體需求,那麼你就被塞滿了(而SO是毫無意義的)。 – jonrsharpe
你的回答毫無意義。我只是用「解決我的問題」,因爲我沒有得到我已經嘗試過的答案(我總是先Google)。我的問題比這個問題要大得多。但我認爲它非常客觀和簡單,這樣人們可以花更少的時間閱讀,我花更少的時間等待,然後我得到一個可用的代碼,並使用提供的代碼爲我的問題提出解決方案。這是學習的重點。快速和簡單。 –
這不是一個答案,它是一個評論。我很欣賞把這個問題歸結爲核心問題的努力,但是SO在這裏不是**,所以你「花費更少的時間等待,然後......獲得一個可行的代碼」。請參加[旅遊]。 – jonrsharpe