python replace函数 成功 失败_请教下调用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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值