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>How about this?</p>

<pre><code>&gt;&gt;&gt; string1 = "12 pieces"
&gt;&gt;&gt; y = int(''.join([x for x in string1 if x in '1234567890']))
&gt;&gt;&gt; print(y)
12
</code></pre>

<p>or better yet:</p>

<pre><code>&gt;&gt;&gt; string1 = "12 pieces"
&gt;&gt;&gt; y = int(''.join([x for x in string1 if x.isdigit() ]))
&gt;&gt;&gt; print(y)
12
</code></pre>

python