Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6793759
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T18:08:20+00:00 2026-05-26T18:08:20+00:00

Here is a quote from https://stackoverflow.com/users/893/greg-hewgill answer to Explain Python's slice notation . Python

  • 0

Here is a quote from https://stackoverflow.com/users/893/greg-hewgill answer to Explain Python's slice notation.

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.

So when the error is prefered, what is the Pythonic way to proceed ? Is there a more Pythonic way to rewrite this example ?

class ParseError(Exception):
    pass

def safe_slice(data, start, end):
    """0 <= start <= 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

edit: the example was simpler to write using byte strings but my real code is using lists.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T18:08:20+00:00Added an answer on May 26, 2026 at 6:08 pm

    Using a function like safe_slice would be faster than creating an object just to perform the slice, but if speed is not a bottleneck and you are looking for a nicer interface, you could define a class with a __getitem__ to perform checks before returning the slice.

    This allows you to use nice slice notation instead of having to pass both the start and stop arguments to safe_slice.

    class SafeSlice(object):
        # slice rules: http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange
        def __init__(self,seq):
            self.seq=seq
        def __getitem__(self,key):
            seq=self.seq
            if isinstance(key,slice):
                start,stop,step=key.start,key.stop,key.step
                if start:
                    seq[start]
                if stop:
                    if stop<0: stop=len(seq)+stop
                    seq[stop-1]
            return seq[key]
    
    seq=[1]
    print(seq[:-2])
    # []
    print(SafeSlice(seq)[:-1])
    # []
    print(SafeSlice(seq)[:-2])
    # IndexError: list index out of range
    

    If speed is an issue, then I suggest just testing the end points instead of doing arithmetic. Item access for Python lists is O(1). The version of safe_slice below also allows you to pass 2,3 or 4 arguments. With just 2 arguments, the second will be interpreted as the stop value, (similar to range).

    def safe_slice(seq, start, stop=None, step=1):
        if stop is None:
            stop=start
            start=0
        else:
            seq[start]
        if stop<0: stop=len(seq)+stop
        seq[stop-1]        
        return seq[start:stop:step]
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Well, following the discussion here: https://stackoverflow.com/questions/5281903/java-json-parsers-whats-the-abusive-anal-thing-with-the-quote-marks-on-attribu Is there a parser/decoder for JavaScript object literals
I have a problem very similar to the one described here: https://microsoft.public.win32.programmer.kernel.narkive.com/Ly2P8Yp2/prevent-vista-from-marking-my-application-as-non-responding That thread
I am using the blueimp jQuery file upload plug-in located here https://github.com/blueimp/jQuery-File-Upload and according
Here's the line from App.Config: <add key=CheckFileFormatString value=P{0}\t&quot;{1}, {2}&quot;\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}/> Here's the code that puts
Here is a simplification of my database: Table: Property Fields: ID, Address Table: Quote
Quite new to maven here so let me explain first what I am trying
I am trying to retrieve a stock quote from Yahoo! finance using Flex. I
Here is the implementation of the dictionary without any compaction support. This quote is
I found this thread here: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=16836 I have exactly the same problem. Quote: Rob
There is a jQuery quiz posted on the W3Schools site here... http://www.w3schools.com/quiztest/quiztest.asp?qtest=jQuery Question #16

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.