How to break the string into pieces and assign the values to the substrings preceding the number in the originial string
<p>I want to break the string into pieces (delimiters are space and <code>/</code>) and assign values to the sub-strings every time a float or int follows the string:</p>

<p>For example, the string could be:</p>

<p>'ABC 12/5 a1 b-2.5 c34.5d54'</p>

<p>Using this, I want the output as:</p>

<p><code>somelist=['ABC', '12', '5']</code>, and 
<code>a=1, b=-2.5, c=34.5, d=54</code></p>

<p>I propose this script:</p>

<pre><code>import re

s = 'ABC 12/5 a1 b-2.5 c34.5d54'
parts = re.findall('([a-z]+)(-?\d+(?:\.\d+)?)|([^ /]+)', s)
somelist = [rest for (key, value, rest) in parts if key == '']
vars = dict((key, float(value)) for (key, value, rest) in parts if key != '')

print(somelist)
print(vars)
</code></pre>

<p>Output:</p>

<pre><code>['ABC', '12', '5']
{'c': 34.5, 'd': 54.0, 'a': 1.0, 'b': -2.5}
</code></pre>

<p>The "variables" are in fact output as dictionary keys, which I think is more appropriate.</p>

<h3>Explanation</h3>

<p>This regular expression:</p>

<pre><code>([a-z]+)(-?\d+(?:\.\d+)?)|([^ /]+)
</code></pre>

<p>will somehow match anything that is not a space or slash. First it tries to match the part before the <code>|</code>:</p>

<pre><code>([a-z]+)(-?\d+(?:\.\d+)?)
</code></pre>

<p>This will match any sequence of letters followed by a number. The letters are captured in the first group (cf. the parentheses), and the number part in the second one. The number can optionally have a minus sign (<code>-?</code>) and/or a fractional part (<code>(?:\.\d+)?</code>), which is not captured in a separate group (hence the <code>?:</code>).</p>

<p>If that fails, the other part of the regular expression kicks in:</p>

<pre><code>([^ /]+)
</code></pre>

<p>This captures anything up to the next delimiter into the third capture group.</p>

<p>Now <code>findall</code> makes a nice array of this, with each part ending up at the corresponding index of each sub array.</p>

<p>The two list comprehensions each take care of the two different cases and gather those results in either an array (where the third capture group was matched) or a dict (where the first two were matched).  </p>

python regex