2015-08-25 60 views
0

代碼用途:測試單個字符串中的多個子字符串?

  1. 要求用戶輸入文件名。
  2. 如果該文件名包含某些子字符串,則該文件名無效。該程序「拒絕」並要求提供新文件名。
  3. 如果文件名不包含那些子字符串,那麼文件名是有效的,程序「接受」它。

嘗試1

while True: 
    filename = raw_input("Please enter the name of the file:") 

    if "FY" in filename or "FE" in filename or "EX1" in filename or "EX2" in filename: 
     print "Sorry, this filename is not valid." 
    else: 
     print "This filename is valid" 
     break 

(我要離開了的情況下檢查輸入只是爲了保持乾淨的例子)。

我的問題是將多個子字符串與輸入文件名進行比較。我想保留所有的子字符串而不是有一個巨大的if or行。我認爲,如果需要的話,接管代碼的人可以更容易地找到並添加元組,而不必擴展條件語句。

嘗試2(與元組):

BAD_SUBSTRINGS = ("FY", "FE", "EX1","EX2") 

while True: 
    valid = True 
    filename = raw_input("Please enter the name of the file:") 

    for substring in BAD_SUBSTRINGS: 
     if substring in filename: 
      valid = false 
      break 

    if not valid: 
     print "Sorry, this filename is not valid" 
    else: 
     print "This filename is valid" 
     break 

但我覺得嘗試2是沒有辦成我想要什麼的最Python的方式?如果可能的話,我想避免for循環和valid布爾值。

有什麼辦法可以讓嘗試2更緊湊?或者我應該回到嘗試1?

回答

3

這個怎麼樣?

BAD_SUBSTRINGS = ("FY", "FE", "EX1","EX2") 

while True: 
    filename = raw_input("Please enter the name of the file:") 

    if any(b in filename for b in BAD_SUBSTRINGS): 
     print("Sorry, this filename is not valid") 
    else: 
     print("This filename is valid") 
     break 
+0

謝謝!我不知道「any」關鍵字。我現在要閱讀它。 – andraiamatrix

+1

請查看'all'關鍵字,而您在那裏:-) –

+0

@andraiamatrix:'any'不是關鍵字,它是一個內置函數。 – martineau

相關問題