re.search() if result is None
<p>How to make this pythonic?</p>

<pre><code>def money_from_string(s):
    gold = re.search("([0-9]+)g", s)
    silver = re.search("([0-9]+)s", s)
    copper = re.search("([0-9]+)c", s)
    s = re.sub("[0-9]+g", "", s)
    s = re.sub("[0-9]+s", "", s)
    s = re.sub("[0-9]+c", "", s)
    assert (len(s.strip()) == 0) # should be 0

    return (gold.group() or 0) * 10000 + (silver.group() or 0) * 100 + (copper.group() or 0)
</code></pre>

<p>This doesn't work because if <code>gold</code> is <code>None</code>, <code>gold.group()</code> will throw an error.</p>

<p>Input examples &amp; expected outputs:</p>

<pre><code>s = "15g17s5c" -&gt; 150000 + 1700 + 5 -&gt; 151705
s = "15g5s"    -&gt; 150000 + 500      -&gt; 150500
s = "15g"      -&gt; 150000            -&gt; 150000
s = "17s5c"    -&gt; 1700 + 5          -&gt; 1705
s = "5c"       -&gt; 5                 -&gt; 5
</code></pre>

<p>Note that I do appropriate checks on the input, to ensure that it actually is of correct format. Ie. it has match:</p>

<pre><code>MONEY_PATTERNS = [
    "([0-9]+g[ ]*[0-9]+s[ ]*[0-9]+c)", # g / s / c
    "([0-9]+g[ ]*[0-9]+s)", # g / s
    "([0-9]+g[ ]*[0-9]+c)", # g / c
    "([0-9]+s[ ]*[0-9]+c)", # s / c
    "([0-9]+g)", # g
    "([0-9]+s)", # s
    "([0-9]+c)", # c
]
</code></pre>

<p>If the value returned is <code>None</code>, you can simply check for none and replace it with <code>0</code>. This seems apt to what your are trying to do.</p>

<pre><code>def money_from_string(s):
    gold = re.search("([0-9]+)g", s)
    silver = re.search("([0-9]+)s", s)
    copper = re.search("([0-9]+)c", s)
    if str(gold) in 'None':
        gold = 0
    if str(silver) in 'None':
        silver = 0
    if str(copper) in 'None':
        copper = 0
    s = re.sub("[0-9]+g", "", s)
    s = re.sub("[0-9]+s", "", s)
    s = re.sub("[0-9]+c", "", s)
    assert (len(s.strip()) == 0) # should be 0

    return ((gold.group() * 10000 + silver.group() * 100 + copper.group())
</code></pre>

python