2016-11-23 52 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