title: Pythonic way to have a "size safe" slicing
body: <p>Here is a quote from <a href="https://stackoverflow.com/users/893/greg-hewgill">https://stackoverflow.com/users/893/greg-hewgill</a> answer  to <a href="https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation">Explain Python&#39;s slice notation</a>.</p>
  
  <blockquote>
    <p>Python is kind to the programmer if there are fewer items than you ask
    for. For example, if you ask for a[:-2] and a only contains one
    element, you get an empty list instead of an error. Sometimes you
    would prefer the error, so you have to be aware that this may happen.</p>
  </blockquote>
  
  <p>So when the error is prefered, what is the Pythonic way to proceed ? Is there a more Pythonic way to rewrite this example ?</p>
  
  <pre class="lang-py prettyprint-override"><code>class ParseError(Exception):
      pass
  
  def safe_slice(data, start, end):
      """0 &lt;= start &lt;= end is assumed"""
      r = data[start:end]
      if len(r) != end - start:
          raise IndexError
      return r
  
  def lazy_parse(data):
      """extract (name, phone) from a data buffer.
      If the buffer could not be parsed, a ParseError is raised.
  
      """
  
      try:
          name_length = ord(data[0])
          extracted_name = safe_slice(data, 1, 1 + name_length)
          phone_length = ord(data[1 + name_length])
          extracted_phone = safe_slice(data, 2 + name_length, 2 + name_length + phone_length)
      except IndexError:
          raise ParseError()
      return extracted_name, extracted_phone
  
  if __name__ == '__main__':
      print lazy_parse("\x04Jack\x0A0123456789") # OK
      print lazy_parse("\x04Jack\x0A012345678") # should raise ParseError
  </code></pre>
  
  <p>edit: the example was simpler to write using byte strings but my real code is using lists.</p>