2008-12-02 85 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之前執行這些操作的唯一方法 - 它們已經作爲方法添加到字符串中。