title: Matching and reconstructing a pair of strings in Python based on a conditional
body: <p>I have the following pair of short strings in Python3.x, whose lengths must be equal:</p>
  
  <pre><code>string_a = 'he_lo_world'
  string_b = 'hi_low_oldd'
  </code></pre>
  
  <p>I would like to <em>quickly as possible</em> create a "summary string" based on how the characters in the pair match, given the following rules:</p>
  
  <p>(1) If the characters are the same, the new letter is S (same). Unless the matching characters are <code>_</code>, then it is U (underscore). </p>
  
  <p>(2) Otherwise, the characters don't match. If there's no match, the letter is N (no match). If <code>string_a</code> has <code>_</code> and <code>string_b</code> does not, it is <code>A</code>. If <code>string_b</code> has <code>_</code> and <code>string_a</code> does not, it is <code>B</code>.</p>
  
  <p>For the pair above, the string would be: </p>
  
  <pre><code>SNUSSABSNNS
  </code></pre>
  
  <p>To construct this string, I think multiple if/for statements will be too inefficient.</p>
  
  <p>Using the list comprehension and itertools example here, <a href="https://stackoverflow.com/questions/19717142/trying-to-find-a-match-in-two-strings-python">Trying to find a match in two strings - Python</a></p>
  
  <pre><code>import itertools
  string_a = 'he_lo_world'
  string_b = 'hi_low_oldd'
  
  same = [ i for i,x in enumerate(itertools.izip(string_a,string_b)) if all(y==x[0] for y in x)]
  
  print(same) ## [0, 2, 3, 4, 7, 10]
  </code></pre>
  
  <p>I can get the indices of the matches. (The <code>_==_</code> exception would require a conditional in the list comprehension, so index 2 shouldn't exist above.)</p>
  
  <p>I'm confused how (A) to re-construct a string based on this list of indices and (B) how do I efficiently deal with non-matching characters? </p>