2008-12-02 100 views
10

有一两件事,我不明白...string.split(text)或text.split()有什么区别?

假设你有一个文本 =“Hello World”的,你想拆呢。

在一些地方,我看到要拆分的文本做的人:

string.split(text) 

在其他地方,我看到人们只是在做:

text.split() 

有什么区别?你为什么以某种方式或以其他方式做?你能给我一个关于这个理论的解释吗?

+0

由于'str'是Python中的内建名(type(''== == str)),我用'text'取代了'str'。 – jfs 2008-12-02 15:07:18

回答

21

有趣的是,这两个文档字符串是不完全相同的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. 

进一步挖掘,你会看到这两种形式是完全等价的,string.split(s)实际上是调用s.split()(搜索拆分 -functions)。

12

string.split(stringobj)string模块的一个特性,它必须单独导入。曾几何时,这是拆分字符串的唯一方法。这是你正在看的一些旧代码。

stringobj.split()是字符串对象stringobj的一项功能,它比string模块更新。但是很老,但是。这是目前的做法。

+0

所以当我使用str。split(),为什么eclipse不做自动完成? – UcanDoIt 2008-12-02 11:48:14

4

附加说明:str是字符串类型,正如S.Lott在上面指出的那样。这意味着,这两种形式:

'a b c'.split() 
str.split('a b c') 

# both return ['a', 'b', 'c'] 

...是等价的,因为str.split是未结合的方法,而s.splitstr对象的绑定的方法。在第二种情况下,传入str.split的字符串在该方法中用作self

这并没有太大的区别,但它是Python对象系统工作原理的一个重要特性。

More info about bound and unbound methods.

1

使用哪种你喜欢,但要意识到str.split是做它的推荐方式。 :-)

string.split是做同样事情的一种较旧的方法。

str.split更高效一些(因为您不必导入字符串模块或查找任何名称),但如果您更喜欢string.split,则不足以产生巨大差异。

5

简短回答:字符串模块是在python 1.6之前执行这些操作的唯一方法 - 它们已经作为方法添加到字符串中。