Extract a number from a string, after a certain character
<p>Ayyyy, I need some help. I have the following strings, always in "char,num" format:</p>

<pre><code>s = "abcdef,12"
v = "gbhjjj,699"
</code></pre>

<p>I want to get just the digits after the comma, how do I do that without splitting the string with the comma as a delimiter?</p>

<p>I tried <code>s[-2:]</code> and <code>v[-3:]</code> which works, but how do I make it work without knowing the number of digits?</p>

<p>Assuming:</p>

<ul>
<li>You <em>know</em> there is a comma in the string, so you don't have to search the entire string to find out if there is or not.</li>
<li>You know the pattern is <code>'many_not_digits,few_digits'</code> so there is a big imbalance between the size of the left/right parts either side of the comma.</li>
<li>You can get to the end of the string without walking it, which <a href="http://stackoverflow.com/questions/38043461/time-complexity-of-python-string-index-access">you can in Python because string indexing is constant time</a></li>
</ul>

<p>Then you could start from the end and walk backwards looking for the comma, which would be less overall work <em>for your examples</em> than walking from the left looking for the comma.</p>

<p>Doing work in Python code is way slower than using Python engine code written in C, right? So would it really be faster?</p>

<ol>
<li>Make a string "aaaaa....,12"</li>
<li>use the <code>timeit</code> module to compare each approach - split, or right-walk. </li>
<li>Timeit does a million runs of some code.</li>
<li>Extend the length of "aaaaaaaaaaaaaaaa....,12" to make it extreme.</li>
</ol>

<p>How do they compare?</p>

<ul>
<li>String split: 1400 "a"'s run a million times took 1 second.</li>
<li>String split: 4000 "a"'s run a million times took 2 seconds.</li>
<li>Right walk: 1400 "a"'s run a million times took 0.4 seconds. </li>
<li>Right walk: 999,999 "a"'s run a million times took ... 0.4 seconds.</li>
</ul>

<p>!</p>

<pre><code>from timeit import timeit

_split = """num = x.split(',')[-1]"""

_rwalk = """
i=-1
while x[i] != ',':
    i-=1
num = x[i+1:]
"""

print(timeit(_split, setup='x="a"*1400 + ",12"'))
print(timeit(_rwalk, setup='x="a"*999999 + ",12"'))
</code></pre>

<p>e.g.</p>

<pre><code>1.0063155219977489     # "aaa...,12" for 1400 chars, string split
0.4027107510046335     # "aaa...,12" for 999999 chars, rwalked. Faster.
</code></pre>

<p><a href="https://repl.it/D9PX" rel="nofollow">Try it online at repl.it</a></p>

<p>I don't think this is algorithmically better than O(n), but with the constraints of the assumptions I made you have more knowledge than str.split() has, and can leverage that to skip walking most of the string and beat it in practise - and the longer the text part, and shorter the digit part, the more you benefit. </p>

python