Python String Slicing from known word in string
<p>I'm trying to read a variable which is written by another function (outside of my control), to look for the presence of a known word and then to copy a sub string beginning at the known word and ending either at the end of the line or a <code>|</code> delimiter.
So I want to write to this variable based on a simple <code>if</code> statement I've written, but at the moment it doesn't take any consideration of what is already in the variable and it needs to.  As the code I'm writing makes use of all sorts of aliases, I've tried to simplify what I am doing below</p>

<p>So, firstly the variable 'devices' is written to elsewhere but available to me.
I'm reading another variable 'area' which if specifically set to '3', I need to write the variable 'devices' with the string of 'box2|box3' (or 'box3|box2' - it doesn't matter) and I can ignore the existing content of 'devices' UNLESS it contains 'box1' in the string.  It may appear anywhere within the string and will also be appended by other data, but it always either finishes at the end of the line, OR by a <code>|</code> delimiter.  So I need to read the entire variable, look for the presence of 'box1' and read as many characters into another variable up until the end of the line of it hits the <code>|</code> delimiter.</p>

<p>The only code I can really share here is this:</p>

<pre><code>area = "3"
if area == "3":
    devices = "box2|box3"
print devices
</code></pre>

<p>Let's say that 'devices' contains 'box5|box6_standard|box9|box8_ex_345|box1_182', I need to extra box1_182 from that string (and append it back in when I write 'devices' variable - I don't need to worry about any other pre-existing content of that variable.</p>

<p>As another example, the existing 'devices' variable may contain 'box7|box1_345|box6|box8_ex_345', in this case, I'd need to take 'box1_345' and append it to the devices string before I write 'box2|box3' to it ('box2|box3|box1_182')</p>

<p>I'd use regex and the <code>in</code> word to check if <code>devices</code> has 'box1'. If so then simply append it to the new <code>devices</code> string</p>

<pre><code>import re

devices='box5|box6_standard|box9|box8_ex_345|box1_182'
area = "3"
if area == "3":
    tdevices = "box2|box3"
    if 'box1' in devices:
        t=re.search('box1[0-9_:a-zA-Z]*', devices)
        devices=tdevices+'|'+t.group()
    else:
        devices=tdevices
print devices
</code></pre>

python string slice