Replace numbers of varying length in a string
<p>I have strings like this in a file:</p>

<pre class="lang-none prettyprint-override"><code>  2381         OH    209    SER     OG   1049    -0.6546         16   ; qtot 1.543
</code></pre>

<p>and I want to replace some numbers (the 1st and the 6th, "2381" &amp; "1049") with different ones, but keeping the alignment, i.e. adding or removing blank spaces before the numbers as needed. That is, I would replace <code>2381</code> with <code>__24</code> (<code>_</code> is a blank) or <code>_1049</code> with <code>37628</code>.</p>

<p>I could hard-code the exact positions of each number, but those could be different with different files, and I'd like something more versatile.</p>

<p>Can anyone help me doing this in python? Say the code is something like:</p>

<pre><code># list_a and list_b contain two different mappings between integer numbers
for line in file:
  (a, b) = (int(line.split()[0]), int(line.split()[5]))
  c = list_a[a]
  d = list_b[b]
  # create "modline", as "line" where (a,b) are replaced with (c,d)
  print modline
</code></pre>

<p>In case it matters, the mappings <code>list_a</code> and <code>list_b</code> are just the order of appearance of the numbers <code>a</code>, <code>b</code>. So, if the input file has:</p>

<pre class="lang-none prettyprint-override"><code>  2381         OH    209    SER     OG   1049    -0.6546         16   ; qtot 1.543
  2382         HO    209    SER     HG   1049     0.4275      1.008   ; qtot 1.971
  2379          C    209    SER      C   1048     0.5973      12.01   ; qtot 2.568
  2380          O    209    SER      O   1048    -0.5679         16   ; qtot 2
</code></pre>

<p>I want it to become:</p>

<pre class="lang-none prettyprint-override"><code>     1         OH    209    SER     OG      1    -0.6546         16   ; qtot 1.543
     2         HO    209    SER     HG      1     0.4275      1.008   ; qtot 1.971
     3          C    209    SER      C      2     0.5973      12.01   ; qtot 2.568
     4          O    209    SER      O      2    -0.5679         16   ; qtot 2
</code></pre>

<p>because <code>2381</code> appears 1st, <code>2380</code> appears 4th; <code>1049</code> appears 1st (in its column), etc. So <code>list_a[2381] = 1</code> and <code>list_b[1049] = 1</code>.</p>

<p>But I think I know how to do that, my problem now is actually replacing the numbers in the strings, taking into account the variable number of spaces.</p>

<p>I should add that there's no guarantee that the numbers are unique in each line, so I can't simply rely on regex match. I have to replace the 1st and 6th numbers, not "every (or the first) instance of <code>2381</code>"</p>
