I'm new to Python and stackoverflow and I'm defining a Python function similar to the inbuilt find() that takes a string and a substring as an argument and two optional arguments specifying the starting and the ending index. I want to keep the latter two arguments optional by specifying default parameters. But I want the ending index to be the length of the first argument by default:

    def search(string, substr, start = 0, end = len(string)):
        lenss = len(substr)
        while start < end:
            if string[start : lenss] == substr:
                return start
            start += 1
            lenss += 1
        return False

But this gives me an error:

Traceback (most recent call last):
    def search(string, substr, start = 0, end = len(string)):
NameError: name 'string' is not defined

What I have tried is setting the last parameter to None and adding a guardian:

def search(string, substr, start = 0, end = None):
    if end is None:
           end  = len(string)
    lenss = len(substr)
    while start < end:
        if string[start : lenss] == substr:
            return start
        start += 1
        lenss += 1
    return False

This gets the job done but I wanted to know if there is a more efficient way to do this and is there a way to assign one parameter to an another one of the same function. Thanks in advance.

1 Answers

1
ruohola On Best Solutions

The way you're doing it here is a good and correct way to do it:
(cleaned up spacing a bit to be more conventional)

def search(string, substr, start=0, end=None):
    if end is None:
        end = len(string)

An other way it's commonly done is:

def search(string, substr, start=0, end=None):
    end = len(string) if end is None else end

Unfortunately there's really no other good way; a function parameter cannot refer to another parameter, since the default parameter values are evaluated only when the function is defined. When evaluting them on the definition it's not possible to evaluate end=len(string), since it cannot be know what string is when it's passed to the function.