Matching multiple strings
<p>I am learning Python string operations and trying to convert delimited text into variables.</p>

<p>i.e. <code>"On Tap: 20 | Bottles: 957 | Cans: 139"</code></p>

<p>This string should assign value of 20 to Tap, 957 to Bottles, and 139 to Cans. This string is not fixed and may vary (for example 3 values or 0, also position of Tap, Bottles or Cans can be interchanged).</p>

<p>So far I have developed this:</p>

<pre><code>import re

strEx = "On Tap: 20 | Bottles: 957 | Cans: 139"
barServingText = strEx.split('|')
print(barServingText)
for i in barServingText:
    print (i)
    if i.find("Bottles"):
        print("Found Bottles")
        Bottles = re.sub('[^0-9]*','',i)
        print(Bottles)
    elif i.find("Cans"):
        print("Found Cans")
        Cans = re.sub('[^0-9]*','',i)
        print(Cans)
    elif i.find("Tap"):
        print("Found Tap")
        Tap = re.sub('[^0-9]*','',i)
        print(Tap)
</code></pre>

<p>However it is not working as per my expectations and reassigning the value of Bottles every time.</p>

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>['On Tap: 20 ', ' Bottles: 957 ', ' Cans: 139']
On Tap: 20
Found Bottles
20
 Bottles: 957
Found Bottles
957
 Cans: 139
Found Bottles
139
</code></pre>

<p>I have included many <code>print</code> statements to debug the code. My purpose is just to assign values to proper variables.</p>

<p><code>find</code> returns <code>-1</code> when it can't find string and <code>-1</code> is treated as <code>True</code> (<code>bool(-1)</code> gives <code>True</code>) so you have to use <code>find(...) != -1</code></p>

<pre><code>import re

strEx = "On Tap: 20 | Bottles: 957 | Cans: 139"
barServingText = strEx.split('|')
print(barServingText)
for i in barServingText:
    print (i)
    if i.find("Bottles") != -1:
        print("Found Bottles")
        Bottles = re.sub('[^0-9]*','',i)
        print(Bottles)
    elif i.find("Cans") != -1:
        print("Found Cans")
        Cans = re.sub('[^0-9]*','',i)
        print(Cans)
    elif i.find("Tap") != -1:
        print("Found Tap")
        Tap = re.sub('[^0-9]*','',i)
        print(Tap)
</code></pre>

<hr>

<p>BTW: with your data you don't need <code>re</code>. You can use <code>split</code> (and <code>strip</code>)</p>

<pre><code>Bottles = i.split(':')[1].strip()

Cans = i.split(':')[1].strip()

Tap = i.split(':')[1].strip()
</code></pre>

python regex