我正在嘗試編寫一個函數,允許用戶輸入名稱或電話號碼,檢查它是否存在於文件中,以及是否打印在找到該元素的整個行中。我至今:如果在Python中找到部分行,從文件打印行
def searchPlayer():
with open("players.txt") as f:
data = f.readlines()
print "Enter 0 to go back"
nameSearch = str(raw_input("Enter player surname, forname, email, or phone number: "))
if any(nameSearch in s for s in data):
#Finding the element in the list works
#Can't think of a way to print the entire line with the player's information
else:
print nameSearch + " was not found in the database"
文件的格式像這樣:
Joe;Bloggs;[email protected];0719451625
Sarah;Brown;[email protected];0749154184
所以,如果nameSearch ==喬,輸出應該是Joe;Bloggs;[email protected];0719451625
任何幫助,將不勝感激,謝謝
問題是'any(...)'不會告訴你哪一行匹配。將它解開成一個循環,你會發現它更容易做到。 – alexis