请教下调用python string模块的replace方法出错的原因

直接调用没有问题

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
阅读 14.1k
2 个回答

没有恶意,但我真的怀疑楼上两位并不太了解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]

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题