Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem with using</p> <pre><code>re.sub(r'_thing_', temp, template) </code></pre> <p>is that <em>every</em> occurrence of <code>_thing_</code> is getting replaced with the same value, <code>temp</code>.</p> <p>What we desire for here is a <code>temp</code> value that can change with each match. </p> <p><a href="http://docs.python.org/2/library/re.html#re.sub" rel="nofollow"><code>re.sub</code> provides such a facility</a> through the use of a callback function as the second argument, rather than a string like <code>temp</code>.</p> <p>The callback is simply a function that takes one argument, the match object, and returns the string we desire for that match.</p> <pre><code>def replacer(match): return ... </code></pre> <p>Now what to put in place of the ellipsis? We can use an <code>iter</code> here:</p> <pre><code>In [27]: math6 = ['chapter1', 'chapter2', 'chapter3', 'chapter1-3test'] In [28]: math6 = iter(math6) In [29]: next(math6) Out[29]: 'chapter1' In [30]: next(math6) Out[30]: 'chapter2' </code></pre> <p>So what we really want is a callback that looks like this:</p> <pre><code>def replacer(match): return next(data) </code></pre> <p>But we have more than one set of data: <code>math6</code> and <code>math4</code>, for example. So we need a callback factory: a function that returns a callback given <code>data</code>:</p> <pre><code>def replace_with(data): def replacer(match): return next(data) return replacer </code></pre> <hr> <p>Putting it all together,</p> <pre><code>import re math6 = iter(['chapter1', 'chapter2', 'chapter3', 'chapter1-3test']) math4 = iter(['chapter1.1', 'chapter1.2-3', 'chapter2']) text = r''' \begin{tabular}{|p{0.7in}|p{0.8in}|p{2.2in}|p{.9in}|p{2.6in}|p{1.6in}|} 6${}^{th}$ Math \newline M\newline &amp; _math6_&amp; 6${}^{th}$ Math \newline W \newline &amp; _math6_ &amp; 6${}^{th}$ Math \newline F \newline &amp; _math6_ &amp; 4${}^{th}$ Math \newline M\newline &amp; &amp; _math4_ &amp; 4${}^{th}$ Math \newline W\newline &amp; &amp; _math4_ &amp; \end{tabular} ''' def replace_with(data): def replacer(match): return next(data) return replacer for pat, data in [(r'_math6_', math6), (r'_math4_', math4)]: text = re.sub(pat, replace_with(data), text) print(text) </code></pre> <p>yields</p> <pre><code>\begin{tabular}{|p{0.7in}|p{0.8in}|p{2.2in}|p{.9in}|p{2.6in}|p{1.6in}|} 6${}^{th}$ Math \newline M\newline &amp; chapter1&amp; 6${}^{th}$ Math \newline W \newline &amp; chapter2 &amp; 6${}^{th}$ Math \newline F \newline &amp; chapter3 &amp; 4${}^{th}$ Math \newline M\newline &amp; &amp; chapter1.1 &amp; 4${}^{th}$ Math \newline W\newline &amp; &amp; chapter1.2-3 &amp; \end{tabular} </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload