CAVS CAVS - 12 days ago 4
Python Question

Same method for the Functions Python

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


The above functions do same thing except the symbols are different, so i want to create an extra function(dont know how to do it) that would accomplish what im trying to do and then call it inside both of the functions

Answer

Don't do that, if both functions perform the exact same operation you only need one function with symbols as an extra argument:

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

Then call it as function("foo", "%") and function("bar", "!") respectively.

Comments