Removing parts of a string after certain chars in Python
<p>New to Python.</p>

<p>I'd like to remove the substrings between the word AND and the comma character in the following string:</p>

<pre><code>MyString = ' x.ABC AND XYZ, \ny.DEF AND Type, \nSome Long String AND Qwerty, \nz.GHI AND Tree \n'
</code></pre>

<p>The result should be:</p>

<pre><code>MyString = ' x.ABC,\ny.DEF,\nSome Long String,\nz.GHI\n'
</code></pre>

<p>I'd like to do it without using regex.</p>

<p>I have tried various methods with splits and joins and indexes to no avail.</p>

<p>Any direction appreciated.</p>

<p>Thanks.</p>

<p>You can split the string into lines, and further split the lines into words and use <a href="https://docs.python.org/2/library/itertools.html#itertools.takewhile" rel="nofollow"><code>itertools.takewhile</code></a> to drop all words after <code>AND</code> (itself included):</p>

<pre><code>from itertools import takewhile

''.join(' '.join(takewhile(lambda x: x != 'AND', line.split())) + ',\n' 
                                      for line in MyString.splitlines())
</code></pre>

<p>Notice that the newline character and a comma are manually added after each line is reconstructed with <a href="https://docs.python.org/2/library/stdtypes.html#str.join" rel="nofollow"><code>str.join</code></a>.</p>

<p>All the lines are then finally joined using <code>str.join</code>.</p>

python string