日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python replace函数 成功 失败_请教下调用python string模块的replace方法出错的原因

發(fā)布時間:2024/9/15 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python replace函数 成功 失败_请教下调用python string模块的replace方法出错的原因 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

直接調(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。