Difficulty with maxsplit default value for str.split

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sun Sep 24 01:48:22 EDT 2006


I'm having problems passing a default value to the maxsplit argument of
str.split. I'm trying to write a function which acts as a wrapper to
split, something like this:

def mysplit(S, sep=None, maxsplit=None):
    pre_processing()
    result = S.split(sep, maxsplit)
    post_processing()
    return result

But the split method doesn't accept a value of None for maxsplit, and I
don't know what default value I should be using. Passing 0 as the default
isn't correct, because then it splits zero times.

By experimentation, I have discovered that passing -1 as the default
instead of None *appears* to work, but I'm not sure if I can rely on it or
if that is an accidental implementation detail. According to the
documentation at
http://docs.python.org/lib/string-methods.html#string-methods

split([sep [,maxsplit]])
    Return a list of the words in the string, using sep as the delimiter
    string. If maxsplit is given, at most maxsplit splits are done. (thus,
    the list will have at most maxsplit+1 elements). If maxsplit is not
    specified, then there is no limit on the number of splits (all
    possible splits are made).


If I take that literally, then the correct way to wrap split is something
like this:

def mysplit(S, sep=None, maxsplit=None):
    pre_processing()
    if maxsplit is None:
        # don't specify maxsplit
        result = S.split(sep)
    else:
        result = S.split(sep, maxsplit)
    post_processing()
    return result

Is it safe for me to pass -1 as the default to maxsplit, meaning
"unlimited splits"? Should the docs be fixed to mention that?

Thanks,



-- 
Steven.




More information about the Python-list mailing list