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>

<blockquote>
  <p>Is there a way to do that and ignore any chars that are not numbers?</p>
</blockquote>

<p>Ignoring anything but a digit is, probably, not a good idea. What if a string contains <code>"12 pieces 42"</code>, should it return <code>12</code>, <code>1242</code>, <code>[12, 42]</code>, or raise an exception?</p>

<p>You may, instead, split the string and convert the first element to an <code>int</code>:</p>

<pre><code>In [1]: int('12 pieces'.split()[0])
Out[1]: 12
</code></pre>

python