best way to get an integer from string without using regex
<p>I would like to get some integers from a string (the 3rd one). Preferable without using regex. </p>

<p>I saw a lot of stuff.</p>

<p>my string:</p>

<pre><code>xp = '93% (9774/10500)'
</code></pre>

<p>So i would like the code to return a list with integers from a string. So the desired output would be: <code>[93, 9774, 10500]</code></p>

<p>Some stuff like this doesn't work:</p>

<pre><code>&gt;&gt;&gt; new = [int(s) for s in xp.split() if s.isdigit()]
&gt;&gt;&gt; print new
[]
&gt;&gt;&gt; int(filter(str.isdigit, xp))
93977410500
</code></pre>

<p>Since this is Py2, using <code>str</code>, it looks like you don't need to consider the full Unicode range; since you're doing this more than once, you can slightly improve on <a href="http://stackoverflow.com/a/39369911/364696">polku's answer</a> using <code>str.translate</code>:</p>

<pre><code># Create a translation table once, up front, that replaces non-digits with 
import string
nondigits = ''.join(c for c in map(chr, range(256)) if not c.isdigit())
nondigit_to_space_table = string.maketrans(nondigits, ' ' * len(nondigits))

# Then, when you need to extract integers use the table to efficiently translate
# at C layer in a single function call:
xp = '93% (9774/10500)'
intstrs = xp.translate(nondigit_to_space_table).split() # ['93', '9774', 10500]

myints = map(int, intstrs)  # Wrap in `list` constructor on Py3
</code></pre>

<p>Performance-wise, for the test string on my 64 bit Linux 2.7 build, using <code>translate</code> takes about 374 nanoseconds to run, vs. 2.76 microseconds for the listcomp and <code>join</code> solution; the listcomp+<code>join</code> takes >7x longer. For larger strings (where the fixed overhead is trivial compared to the actual work), the listcomp+<code>join</code> solution takes closer to 20x longer.</p>

<p>Main advantage to polku's solution is that it requires no changes on Py3 (on which it should seamlessly support non-ASCII strings), where <code>str.translate</code> builds the translation table a different way there (<code>str.translate</code>) and it would be impractical to make a translation table that handled all non-digits in the whole Unicode space.</p>

python string int