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