写程式很多时都需要做字串搜寻并取代, 在 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.