How can I reverse parts of sentence in python?
<p>I have a sentence, let's say:</p>

<p>The quick brown fox jumps over the lazy dog</p>

<p>I want to create a function that takes 2 arguments, a sentence and a list of things to ignore. And it returns that sentence with the reversed words, however it should ignore the stuff I pass to it in a second argument. This is what I have at the moment:</p>

<pre><code>def main(sentence, ignores):
    return ' '.join(word[::-1] if word not in ignores else word for word in sentence.split())
</code></pre>

<p>But this will only work if I pass a second list like so:</p>

<pre><code>print(main('The quick brown fox jumps over the lazy dog', ['quick', 'lazy']))
</code></pre>

<p>However, I want to pass a list like this:</p>

<pre><code>print(main('The quick brown fox jumps over the lazy dog', ['quick brown', 'lazy dog']))
</code></pre>

<p>expected result:
<code>ehT quick brown xof spmuj revo eht lazy dog</code></p>

<p>So basically the second argument (the list) will have parts of the sentence that should be ignored. Not just single words.</p>

<p>Do I have to use regexp for this? I was trying to avoid it...</p>

<p>I'm the first person to recommend avoiding regular expressions, but in this case, the complexity of doing without is greater than the complexity added by using them:</p>

<pre><code>import re

def main(sentence, ignores):
    # Dedup and allow fast lookup for determining whether to reverse a component
    ignores = frozenset(ignores)

    # Make a pattern that will prefer matching the ignore phrases, but
    # otherwise matches each space and non-space run (so nothing is dropped)
    # Alternations match the first pattern by preference, so you'll match
    # the ignores phrases if possible, and general space/non-space patterns
    # otherwise
    pat = r'|'.join(map(re.escape, ignores)) + r'|\S+|\s+'

    # Returns the chopped up pieces (space and non-space runs, but ignore phrases stay together
    parts = re.findall(pat, sentence)

    # Reverse everything not found in ignores and then put it all back together
    return ''.join(p if p in ignores else p[::-1] for p in parts)
</code></pre>

python python-3.x