2014-01-24 26 views
1

這裏是Python中的字符串:Python函數的參數和文件混亂

a = "asdf as df adsf as df asdf asd f" 

比方說,我想 「與 」||「 全部替換」,所以我做的:

>>> a.replace(" ", "||") 
'asdf||as||df||adsf||as||df||asdf||asd||f' 

我的困惑是the documentation如下信息:

string.replace(s, old, new[, maxreplace]) 
    Return a copy of string s with all occurrences... 

我可以「忽略」 s,但是基於實況我需要s;但是,我只提供oldnew。我注意到它是這樣的,有很多python文檔;我錯過了什麼?

回答

1

的方法的第一個參數是將被修改的對象(通常稱爲self)的引用,是隱式傳遞當您使用object.method(...)符號。所以這個:

a = "asdf as df adsf as df asdf asd f" 
print a.replace(" ", "||") 

是相同的:

a = "asdf as df adsf as df asdf asd f" 
print str.replace(a, " ", "||") 

str是班上a對象。這只是語法糖。

1

當您調用對象的方法時,該對象將自動作爲第一個參數提供。通常在該方法內,這被稱爲self

所以可以調用函數傳入對象:

string.replace(s, old, new) 

或可以調用對象的方法:

s.replace(old, new) 

兩種功能相同。

+0

它是'str',而不是'string'。 –

5

您正在將str對象方法與string模塊函數混合使用。

你指的文檔是string module documentation.事實上,有稱爲replace字符串模塊中的函數,它接受3(或任選地,4)參數:

In [9]: string 
Out[9]: <module 'string' from '/usr/lib/python2.7/string.pyc'> 

In [11]: string.replace(a, ' ', '||') 
Out[11]: 'asdf||as||df||adsf||as||df||asdf||asd||f' 

astr對象 - (str是一種類型,string是一個模塊):

In [15]: type(a) 
Out[15]: str 

而且str對象具有replace方法。 str方法的文檔是here

+1

我想補充一點,不應該使用'string'模塊,因爲它的大多數功能已經與'str'字符串類+1 –

+0

+1合併了! – tawmas

+0

@StefanoSanfilippo:有一些字符串函數[已棄用](http://docs.python.org/2/library/string.html#deprecated-string-functions),比如'string。atof',但整個模塊不被棄用。當你需要該函數時,這些函數可能很有用,而不是綁定到特定'str'的​​方法,並且常量也很有用。 – unutbu