Python 字串搜尋並取代 | python replace特定
寫程式很多時都需要做字串搜尋並取代,在Python內很簡單,只要用內建的replace方法便可實現。語法以下是replace()的語法:str.replace(old,new[,max]) str.replace(old,new[,max]) 參數:old−原來字串,找出並用新字串取代.new−替換字串,替換在原來字串內.max−如果有定義max參數,只會取代最初出現的“max”次數的字串.例子:#!/usr/bin/pythonstr="test,test."printstr.replace("test","testing")printstr.replace("test","testing",1) #!/usr/bin/python str="test,test."printstr.replace("test","testing"...
寫程式很多時都需要做字串搜尋並取代, 在 Python 內很簡單, 只要用內建的 replace 方法便可實現。
語法
以下是 replace() 的語法:
str.replace(old, new[, max])
str.replace(old, new[, max])
參數:
old − 原來字串, 找出並用新字串取代.
new − 替換字串, 替換在原來字串內.
max − 如果有定義 max 參數, 只會取代最初出現的 “max” 次數的字串.
例子:
#!/usr/bin/python str = "test, test." print str.replace("test", "testing") print str.replace("test", "testing", 1)
#!/usr/bin/python
str = "test, test."
print str.replace("test", "testing")
print str.replace("test", "testing", 1)
輸出結果:
testing, testing.testing, test.
你可能感興趣的內容: