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>Instead of placeholders, why not just initially reverse any phrase that you want to be around the right way, then reverse the whole string:</p>

<pre><code>def main(sentence, ignores):
    for phrase in ignores:
        reversed_phrase = ' '.join([word[::-1] for word in phrase.split()])
        sentence = sentence.replace(phrase, reversed_phrase)

    return ' '.join(word[::-1] for word in sentence.split())

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

<p>returns:</p>

<pre><code>ehT quick nworb xof spmuj revo eht lazy god
ehT quick brown xof spmuj revo eht lazy dog
</code></pre>

python python-3.x