2016-11-23 55 views
0
def function1(string): 
    symbol="%" 
    new_string=string.split() 
    for item in new_string: 
     if item.startswith(symbol): 
     #etc 

def function2(string): 
    symbol="!" 
    new_string=string.split() 
    for item in new_string: 
     if item.startswith(symbol): 
     #etc 

上述功能做同樣的事情,除了符號是不同的,所以我想創建一個額外的功能(不知道如何做到這一點),這將完成什麼即時試圖做的,然後同樣的方法稱之爲內兩者的功能的功能Python的

回答

3

不這樣做,如果這兩個函數執行完全相同的操作來你只需要一個symbols函數作爲額外的參數:

def function(string, symbol): 
    new_string=string.split() 
    for item in new_string: 
     if item.startswith(symbol): 
     #etc 

然後把它作爲function("foo", "%")function("bar", "!") re spectively。

+0

對於我的任務,我需要兩個函數,一個用於獲取以%開頭的字符串,另一個用於以字符串開頭的字符串! – CAVS