2014-01-29 43 views
0
elif search.lower() == "m": 
    DMY = input("please enter your date of birth you are looking for (date/month/year) : ") 
    DMY = DMY.split("/") 
    DMY = DMY[1] 

    for line in open("datafile.txt"): 
     if DMY in line: 
      print(line) 
+1

使用're'或'進行驗證 –

+0

或者乾脆datetime'模塊'如果不是「/ 「在DMY中:......'...... – Torxed

+1

代碼應該被重新設計以整齊地分離輸入,驗證和操作的步驟:第一行的'elif'告訴我,你在一個'如果'分支... – Don

回答

6

您可以使用異常處理:

DMY = input("please enter your date of birth you are looking for (date/month/year) :` ") 
DMY = DMY.split("/", 2) 
try: 
    DMY = int(DMY[1]) 
except (IndexError, ValueError): 
    # User did not use (enough) slashes or the middle value was not an integer 
    print("Oops, did you put in an actual date?") 

或者你可以嘗試和解析日期:

import datetime 

DMY = input("please enter your date of birth you are looking for (date/month/year) :` ") 
try: 
    DMY = datetime.datetime.strptime(DMY, '%d/%m/%Y').date() 
except ValueError: 
    # User entered something that doesn't fit the pattern dd/mm/yyyy 
    print("Oops, did you put in an actual date?") 

後者的優點是,你現在有一個實際datetime.date()對象,它不不僅僅是檢查用戶輸入的斜線和整數,它還驗證輸入的值實際上可以解釋爲日期。 30/02/4321不會解析,因爲沒有月30日,甚至在今年4321

+0

+1代碼是完美的,但我喜歡用while循環強制用戶輸入所需的格式。這是一個很好的做法? – Llopis

+1

@Llopis:是的,這是很好的做法。使用'while True'循環,繼續詢問,直到您有有效的輸入。然後使用'break'結束循環。 –

1

使用發現:

s = "29/01/2014" 
if s.find("/") == -1: 
    print "No '/' here!" 
else: 
    print "Found '/' in the string." 
相關問題