2016-02-27 34 views
1

我是Python新手。我被困在最後一個問題上,我不知道我做錯了什麼。問題是:Python多個字符串比較不起作用

定義一個函數,用於確定輸入字符串是否以網址形式以「http」開頭並以「.com」「.net」或「.org」結尾。 。如果輸入字符串以這些後綴之一結尾並以「http」開頭,則該函數將返回True,否則它將返回False。

def isCommonWebAddressFormat(inputURL): 

這是我目前在我的Python代碼,但它的轉向了錯誤的結果,當我測試一下:

def isCommonWebAddressFormat(inputURL): 
    #return True if inputURL starts with "http" and ends with ".com" ".net" or ".org" and returns False otherwise 
    outcome = "" 
    if "http" and ".com" in inputURL: 
     outcome = True 
    elif "http" and ".net" in inputURL: 
     outcome = True 
    elif "http" and ".org" in inputURL: 
     outcome = True 
    else: 
     outcome = False 
    return outcome 

當我調用該函數與"www.google.com",結果是True ,儘管它應該是False

+0

使用字符串的'endswith'和'startswith'方法來執行檢查。 –

+0

我該怎麼做?我真的沒有這個計劃的經驗,我在入門級課程,我們沒有在課堂上教過這個,因爲它聽起來很荒謬 –

+0

請[編輯]你的頭銜,以反映你的問題。如果無法找到這個問題,這個問題對任何其他人都沒用,沒有人會去搜索「在一個簡單但有問題的作業問題上需要幫助」。 –

回答

1

這絕對是最常見的錯誤初學者做一個,你需要了解的第一件事情是,所有的對象可以在truth testing使用:

if "http": 
    print("it was true!!") 

那麼你可以考慮的執行順序有條件的,你寫道:

if "http" and ".com" in inputURL 

是相同的:

if ("http") and (".com" in inputURL) 

是因爲"http"始終評估爲真,第二部分是真正貢獻的唯一的事情(這就是爲什麼www.google.com作品)你想代替的是:

if ("http" in inputURL) and (".com" in inputURL): 

雖然startswithendswith方法肯定是因爲它檢查最好只在開頭和結尾:

if inputURL.startswith("http") and inputURL.endswith(".com") 

你可以看到與help功能上這些方法的文檔(以及一切其他蟒蛇):

help(str.startswith) 

幫助上method_descriptor:

startswith(...) S.startswith(前綴[,開始[,結束]) - > BOOL

返回TRUE若S開頭指定的前綴,否則爲False。 使用可選啓動時,測試S從該位置開始。 使用可選結束時,停止在該位置比較S. 前綴也可以是字符串的元組來嘗試。

即使我使用help總是有用的,我纔剛剛得知startswithendswith可以利用字符串的元組嘗試:

S.startswith(("a","b","c")) 

這將如果字符串返回TrueS開始任「a」或「b」或「c」,使用它你可以在一行中編寫你的函數。