How to cast a int from string that contains not only numbers
<p>Casting a string is easy:</p>

<pre><code>string1 = "12"
int1 = int(string1)
</code></pre>

<p>But what if I want to extract the int from</p>

<pre><code>string1 = "12 pieces"
</code></pre>

<p>The cast should return 12. Is there a pythonic way to do that and ignore any chars that are not numbers?</p>

<p>Assuming that the first part of the string is a number, one way to do this is to use a regex match:</p>

<pre><code>import re

def strint(str):
    m=re.match("^[0-9]+", str)
    if m:
        return int(m.group(0))
    else:
        raise Exception("String does not start with a number")
</code></pre>

<p>The advantage of this approach is that even strings with just numbers can be cast easily, so you can use this function as a drop in replacement to <code>int()</code></p>

python