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>Just another idea, reverse every word and then reverse the ignores right back:</p>

<pre><code>&gt;&gt;&gt; from functools import reduce
&gt;&gt;&gt; def main(sentence, ignores):
        def r(s):
            return ' '.join(w[::-1] for w in s.split())
        return reduce(lambda s, i: s.replace(r(i), i), ignores, r(sentence))

&gt;&gt;&gt; main('The quick brown fox jumps over the lazy dog', ['quick brown', 'lazy dog'])
'ehT quick brown xof spmuj revo eht lazy dog'
</code></pre>

python python-3.x