Replacing string in a list of strings
<p>I have problem with my code. In this example it should print out <code>The Wind in the Willows</code>, but it does print <strong>The Wind In The Willows</strong>. I think the problem is that replace function does not execute. I have no idea what's wrong with this code. Please help.</p>

<p>PS. Basic idea of this function is to return title lookalike string with exception (<code>minor_words</code>). <code>Minor_words</code> should be lower case in a title (despite the case if <code>minor_words</code> is the first word in the <code>title</code>)</p>

<pre><code>def title_case(title, minor_words):
    exc = [x for x in title.lower().split() if x in minor_words.lower().split()]
    for string in exc:
        if title.split().index(string) == 0:
            title = title.title()
        else:
            title = title.title().replace(string, string.lower())
    return title


print (title_case('THE WIND IN THE WILLOWS', 'The In'))
</code></pre>

<p>Since you assign to <code>title</code> in the loop, you get the value of title is the same as the value assigned to it by the last time through the loop.</p>

<p>I've done this differently. I loop through all the words in the title (not just the exclusions) and title case those that are not excluded.</p>

<pre><code>def title_case(title, minor_words):
    """Title case, excluding minor words, but including the first 
    word"""

    exclusions = minor_words.lower().split()
    words = title.split()

    # Loop over the words, replace each word with either the title
    # case (for first word and words not in the exclusions list) 
    # or the lower case (for excluded words)
    for i, word in enumerate(words):
        if i == 0 or word.lower() not in exclusions:
            words[i] = words[i].title()
        else:
            words[i] = words[i].lower()

    title = " ".join(words)
    return title


print (title_case('THE WIND IN THE WILLOWS', 'The In'))
</code></pre>

python string