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>If you are worried about using split from the left because of lots of unwanted characters in the beginning, use rsplit.</p>

<pre><code>s = "abcdef,12"
s.rsplit(",", 1)[-1]
</code></pre>

<p>Here, rsplit will start splitting the string from the right and the optional second argument we used will stop rsplit to proceed further than the first comma operator it encountered. </p>

<pre><code>(eg):
s = "abc,def,12"
s.rsplit(",", 1)[-1]
# Outputs 12
s = "abcdef12"
s.rsplit(",", 1)[-1]
# Outputs abcdef12
</code></pre>

<p>This will be lot simpler and cleaner to get the string of numbers in the end rather than doing anything manually.</p>

<p>Not to mention, it will be lot easier if we wish to check whether we get only numbers with this. Even if it is a list of strings.</p>

<pre><code>def get_numbers(string_list, skip_on_error=True):
    numbers_list = []
    for input_string in string_list:
        the_number = input_string.rsplit(",", 1)[-1]
        if the_number.isdigit():
            numbers_list.append(the_number)
        elif skip_on_error:
            numbers_list.append("")
        else:
            raise Exception("Wrong Format occurred: %s" % (input_string))
    return numbers_list
</code></pre>

<p>And if you are looking for even further optimization and sure that most(if not all) strings will be of the correct format, you can even use try except if you are going to go with an integer list instead of string list. Like this:</p>

<pre><code># Instead of the if.. elif.. else construct
try:
    numbers_list.append(int(the_number))
except ValueError:
    if skip_on_error:
        numbers_list.append(0)
    else:
        raise Exception("Wrong Format occurred: %s" % (input_string))
</code></pre>

<p>But always remember the <a href="https://www.python.org/dev/peps/pep-0020/#id3" rel="nofollow" title="Zen of Python">Zen Of Python</a> and using split/rsplit follows these:</p>

<ol>
<li>Beautiful is better than ugly</li>
<li>Explicit is better than implicit</li>
<li>Simple is better than complex</li>
<li>Readability counts</li>
<li>There should be one-- and preferably only one --obvious way to do it</li>
</ol>

<p>And also remember Donald Knuth:</p>

<blockquote>
  <p>We should forget about small efficiencies, say about 97% of the time: <strong>premature optimization is the root of all evil</strong>. Yet we should not pass up our opportunities in that critical 3%</p>
</blockquote>

python