Python Regular Expression; replacing a portion of match
<p>How would I limit match/replacement the leading zeros in e004_n07?  However, if either term contains all zeros, then I need to retain one zero in the term (see example below). For the input string, there will always be 3 digits in the first value and 2 digits in the second value.</p>

<p>Example input and output</p>

<pre><code>e004_n07 #e4_n7
e020_n50 #e20_n50
e000_n00 #e0_n0
</code></pre>

<p>Can this be accomplished with re.sub alone, or do I need to use re.search/re.match?</p>

<p>If your requirement is that you MUST use <code>regex</code>, then below is your regex pattern:</p>

<pre><code>&gt;&gt;&gt; import re
&gt;&gt;&gt; s = 'e004_n07'
&gt;&gt;&gt; line = re.sub(r"0", "", s)
&gt;&gt;&gt; line
'e4_n7'
</code></pre>

<p>However it is recommended not to use regex when there is other efficient way to perform the same opertaion, i.e. using <code>replace</code> function</p>

<pre><code>&gt;&gt;&gt; line = s.replace('0', '')
&gt;&gt;&gt; line
'e4_n7'
</code></pre>

python regex