title: How do I efficiently overlay two strings where one string takes priority over the other?
body: <p>I have two strings that act as buffers for ranges of a file. I want to read from this "file" so as to read bytes from the first string in preference to the second string, where there is overlap.</p>
  
  <p>In the examples below, r1 and r2 each represent ranges of the file, which consist of the string along with start and end offsets. I have formatted the examples to make it clearer where in the file the strings exist.</p>
  
  <pre><code>def prioritized_read(range1, range2, read_start, read_end):
      # This is the bit I don't know how to write
  
  r1 = ("ABCDEF", (0,6))
  r2 = ( "DEF",   (1,4))
  assert prioritized_read(r1, r2, 0, 6) == "ABCDEF"
  
  r1 = ("ABC",    (0,3))
  r2 = ( "DEF",   (1,4))
  assert prioritized_read(r1, r2, 1, 4) == "BCF"
  
  r1 = (  "ABC",  (2,5))
  r2 = ("DEF",    (0,3))
  assert prioritized_read(r1, r2, 0, 4) == "DEAB"
  
  r1 = ( "A",     (1,2))
  r2 = ("DEF",    (0,3))
  assert prioritized_read(r1, r2, 0, 3) == "DAF"
  
  r1 = ("ABC",    (0,3))
  r2 = (   "DEF", (3,6))
  assert prioritized_read(r1, r2, 3, 6) == "DEF"
  </code></pre>
  
  <p><code>read_start</code> and <code>read_end</code> will always be bounded by the endpoints of <code>r1</code> and <code>r2</code>.</p>
  
  <p>The example ranges here are small, but in my application they could be greater than 1 billion, so I'm looking for a solution that is time and memory efficient. </p>
  
  <p>I considered posting this to <a href="https://codegolf.stackexchange.com/">Programming Puzzles &amp; Code Golf</a>. It seems like it should be an easy and obvious process... but it's defeated me.</p>
  
  <p>N.B. I'm not really reading from a file here, so I can't use solutions involving Python file objects. I'm just using files as a convenient analogy.</p>