Skip to main content
 首页 » 编程设计

Python 函数参数和文档混淆

2025年05月04日14jillzhang

这是 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;然而,我只提供old和new。我注意到很多 python 文档都是这样;我错过了什么?

请您参考如下方法:

您将 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' 

a 是一个 str 对象——(str 是一个类型,string 是一个模块):

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

str 对象有一个replace 方法。 str 方法的文档是 here .