Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.split(text) or text.split() : what's the difference?

There is one thing that I do not understand...

Imagine you have a text = "hello world" and you want to split it.

In some places I see people that want to split the text doing:

string.split(text)

In other places I see people just doing:

text.split()

What’s the difference? Why you do in one way or in the other way? Can you give me a theory explanation about that?

like image 904
UcanDoIt Avatar asked Dec 02 '08 11:12

UcanDoIt


1 Answers

Interestingly, the docstrings for the two are not completely the same in Python 2.5.1:

>>> import string
>>> help(string.split)
Help on function split in module string:

split(s, sep=None, maxsplit=-1)
    split(s [,sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string s, using sep as the
    delimiter string.  If maxsplit is given, splits at no more than
    maxsplit places (resulting in at most maxsplit+1 words).  If sep
    is not specified or is None, any whitespace string is a separator.

    (split and splitfields are synonymous)

>>> help("".split)
Help on built-in function split:

split(...)
    S.split([sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator.

Digging deeper, you'll see that the two forms are completely equivalent, as string.split(s) actually calls s.split() (search for the split-functions).

like image 144
csl Avatar answered Oct 08 '22 17:10

csl