def count(word, substring): # string method OP (optional parameters) """Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. >>> count("Hello", "l") 2 >>> count("Hello", "Hell") 1 """ # return word.count(substring) counter = 0 for i in range(len_copy(word)): if word[i:len_copy(substring) + i] == substring: counter += 1 return counter
def ends_with(end_word, word): """ Return True if and only if word ends with end_word. >>> ends_with('world', 'hello world') True >>> ends_with('hello', 'hello world') False >>> ends_with('', '') True >>> ends_with('hello there', 'a') False >>> ends_with('a', 'a') True """ # return word.endswith(end_word) if len_copy(end_word) > len_copy(word): return False return word[len_copy(word) - len_copy(end_word):] == end_word
def center(word, length_needed, padding): # string method """ Return a string with given padding on the edges with desired length if length_needed is odd, padding will be added to the beginning >>> center("name", 4, 'a') 'name' >>> center("name", 8, '*') '**name**' >>> center("name", 9, '*') '***name**' >>> center("name", 8, '**') '**name**' """ #return word.center(length_needed, padding) if length_needed <= len_copy(word): return word for i in range(int((length_needed - len_copy(word)) / len_copy(padding))): if i % 2 == 0: word = padding + word else: word = word + padding return word
def index(obj, objects): # string method """ Return the index of obj in objects or return -1 if not found. >>> index('name', ['phone', 'address', 'name', 'postal code']) 2 >>> index('Hello', ['hello', 'world', 'how', 'are' 'you']) -1 """ # linear search # make a function for range # return objects.index(obj) for i in range(len_copy(objects)): if objects[i] == obj: return i return -1
def starts_with(begin_word, word): """ Return True if and only if word starts with begin_word. >>> starts_with('hello', 'hello world') True >>> starts_with('world', 'hello world') False >>> starts_with('', '') True """ # return word.startswith(begin_word) for i in range(len_copy(begin_word)): if begin_word[i] != word[i]: return False return True