直接调用没有问题
def test1():
test_str="028-123456"
print test_str.replace(old="-",new="")
def test2():
test_str="028-123456"
print test_str.replace("-","")
test2()
结果
Connected to pydev debugger (build 141.1245)
028123456
Process finished with exit code 0
指出参数名进行调用时出错
Traceback (most recent call last):
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 2357, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1777, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Users/function_test/test_builtin_str.py", line 8, in <module>
test1()
File "/Users/function_test/function_test/test_builtin_str.py", line 4, in test1
print test_str.replace(old="-",new="")
TypeError: replace() takes no keyword arguments
没有恶意,但我真的怀疑楼上两位并不太了解Python。
你这么调用在Python中是没问题的,但出现这个问题的真正原因是字符串的
replace
方法不是用Python实现的,而是用C语言实现的,所以它不支持Python里面的
keyword
参数特性。
你可以试一下用
Python版本的replace
:
from string import replace
s = '012-3456'
print replace(s, new='', old='-') # 即使将old和new调换位置一样可以正确替换,输出0123456
这个
replace
方法在
string
模块中(Lib/string.py文件),是对C语言版本的
relace
方法的封装,有兴趣的话你可以去看看它的源码
replace函数在python2.7的文档中描述如下:
str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
在python中的函数参数分为四种:必选参数、默认参数、可变参数、关键字参数
replace函数中old和new输入必选参数,count属于默认参数
你在test1中使用的调用方式必须在函数定义时声明为关键字参数
关键字参数举例:
def test(**kw):
for key in kw:
print "[%s, %s]" % (key, kw[key])
test(x=9)
以上代码输出为[x, 9]