python replace函数 成功 失败_请教下调用python string模块的replace方法出错的原因
直接調(diào)用沒有問題
def test1():
test_str="028-123456"
print test_str.replace(old="-",new="")
def test2():
test_str="028-123456"
print test_str.replace("-","")
test2()
結(jié)果
Connected to pydev debugger (build 141.1245)
028123456
Process finished with exit code 0
指出參數(shù)名進行調(diào)用時出錯
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。
你這么調(diào)用在Python中是沒問題的,但出現(xiàn)這個問題的真正原因是字符串的
replace
方法不是用Python實現(xiàn)的,而是用C語言實現(xiàn)的,所以它不支持Python里面的
keyword
參數(shù)特性。
你可以試一下用
Python版本的replace
:
from string import replace
s = '012-3456'
print replace(s, new='', old='-') # 即使將old和new調(diào)換位置一樣可以正確替換,輸出0123456
這個
replace
方法在
string
模塊中(Lib/string.py文件),是對C語言版本的
relace
方法的封裝,有興趣的話你可以去看看它的源碼
replace函數(shù)在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中的函數(shù)參數(shù)分為四種:必選參數(shù)、默認參數(shù)、可變參數(shù)、關(guān)鍵字參數(shù)
replace函數(shù)中old和new輸入必選參數(shù),count屬于默認參數(shù)
你在test1中使用的調(diào)用方式必須在函數(shù)定義時聲明為關(guān)鍵字參數(shù)
關(guān)鍵字參數(shù)舉例:
def test(**kw):
for key in kw:
print "[%s, %s]" % (key, kw[key])
test(x=9)
以上代碼輸出為[x, 9]
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的python replace函数 成功 失败_请教下调用python string模块的replace方法出错的原因的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 树莓派 rfid_树莓派工控机做Modb
- 下一篇: python 设置x轴_python m