def substitute(text, replacements):
    """Apply the given replacements to the string `text`."""
    index = 0
    while index < len(text):
        search_index = len(text)
        search_text = None
        for search in replacements.keys():
            i = text.find(search, index, search_index + len(search))
            if 0 <= i < search_index:
                search_index = i
                search_text = search
        if search_index == len(text):
            break
        replacement = replacements[search_text]
        text = text[:search_index] + replacement + text[search_index + len(
            search_text):]
        index = search_index + len(replacement)
    return text
