2015-12-03 25 views
-1

我有一個數據庫,我希望能夠搜索,即一個名稱,如果名稱是馬克·克拉姆,它會顯示用戶使用該名稱,我並不需要它所有名字都帶有「Mark」或「Kram」但只有輸入的字符串。我目前的代碼只顯示每個用戶,而不是我搜索的用戶?Python中找到嵌套元組字符串

(基於評論編輯,刪除多餘的代碼)

find = str(input("Enter the name of the employee you would like to search for: ")) 
    print() 
    for find in record: 
     print("Employee Name: " + find[0]) 
     print("Job title: " + find[1]) 
     #more prints 
+0

你指的是選擇B還是C?看起來選擇b旨在打印所有員工姓名... –

+0

要選擇c,它要求輸入以搜索員工。 B應該顯示所有員工 – Xrin

+0

@Xrin你現在有3個答案,並且你的問題似乎被正確解決;如果你接受其中的一個,這將是很好的(點擊答案左邊的灰色厚點)。 – iled

回答

1

您必須查找每個元組中第一項(全名)的匹配。

elif choice == "c": 
    find = str(input("Enter the name of the employee you would like to search for: ")) 
    print() 
    for employee in record: 
     if employee[0] == find: 
      print("Employee Name: " + employee[0]) 
      print("Job title: " + employee[1]) 
      print("Full time: " + employee[2]) 
      print("Hourly Rate: " + employee[3]) 
      print("Years of service: " + str(employee[4])) 
      print() 

您的代碼是一個很好的例子,開始瞭解class es。

0

取決於有多少條記錄,我會走簡約路線,並通過尋找僱員的姓名記錄迭代:

empName = "Mark Kram" 
for record in records: 
    if record[0] == empName: 
    print "we found the employee!" 
    print record #print the whole employee record 
+0

我明白了,既然已經有添加員工的選項,記錄的數量也會有所不同。但是,如果'記錄在記錄中',因爲我已經有記錄定義了 – Xrin

+0

,所以我用{記錄在記錄中},因爲它讀得更好......當你迭代列表時,名爲var的單數通常會首先出現,而名爲var的複數通常會出現在下一個。 –

+0

另外,您不應該遍歷所有員工以查找單個員工,而應該有另一個數據庫查詢返回單個員工。 –

0

這是因爲您正在迭代所有記錄並在沒有任何條件的情況下進行打印。您也會立即覆蓋查詢字符串。

elif choice == "c": 
    find = str(input("Enter the name of the employee you would like to search for: ")) 
    print() 
    for employee in record: 
     if employee[0] == find: 
      print("Employee Name: " + employee[0]) 
      print("Job title: " + employee[1]) 
      print("Full time: " + employee[2]) 
      print("Hourly Rate: " + employee[3]) 
      print("Years of service: " + str(employee[4])) 
      print() 
+0

我試過這個說實話,它只是返回空白,即我添加兩個記錄,搜索一個名稱,它什麼也沒有顯示。 – Xrin

+1

find [n]需要成爲員工[n]。 – digglemister

+0

第一步,將你輸入的整個腳本刪減到一個最小的激勵範例中。因此,例如,手動定義'表'的兩個'行',然後運行查找循環。我還編輯了我的代碼,因爲我忘記了更改一些'find'實例。 – Tunisia