Python字符串替换

Python字符串替换教程

Python 中,我们需要将一个 字符串 替换成另一个字符串,使用 replace 函数

Python replace()函数详解

定义

replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数 max,则替换不超过 max 次。

语法

str.replace(old, new[, max])

参数

参数 描述
str 需要替换的原字符串。
old 将被替换的子字符串。
new 新字符串,用于替换 old 子字符串。
max 可选字符串, 替换不超过 max 次。

返回值

返回替换后的字符串。

案例

替换字符串

使用 replace() 函数,实现字符串全部替换

print("嗨客网(www.haicoder.net)") # 使用 strip() 函数,去除字符串的指定字符 strHaicoder = 'I love python, and study python from haicoder!' print("before replace strHaicoder =", strHaicoder) strHaicoder = strHaicoder.replace("python", "Golang") print("after replace strHaicoder =", strHaicoder)

程序运行后,控制台输出如下:

101 python字符串替换replace.png

首先,我们定义了一个字符串类型的 变量 strHaicoder,并且赋值,接着我们使用字符串的 replace() 函数替换了字符串中的 “python” 为 “Golang”,并使用 print() 函数打印最终结果。

因为,我们没有指定第三个参数,即替换次数,因此,整个字符串中的所有的 “python” 被替换为了 “Golang”。

替换字符串

使用 replace() 函数,实现字符串全部替换

print("嗨客网(www.haicoder.net)") # 使用 strip() 函数,去除字符串的指定字符 strHaicoder = 'I love python, and study python from haicoder!' print("before replace strHaicoder =", strHaicoder) strHaicoder = strHaicoder.replace("python", "Golang", 1) print("after replace strHaicoder =", strHaicoder)

程序运行后,控制台输出如下:

102 python字符串替换replace.png

这次,我们指定了 replace 函数的第三个参数,即,只替换一次,结果,我们发现,整个字符串中的 “python” 只被替换了一次。

Python字符串替换总结

在 Python 中,我们需要将一个字符串替换成另一个字符串,使用 replace 函数。Python replace() 函数语法:

str.replace(old, new[, max])