34. Python replace()

发布时间:2023-12-08

Python replace()

更新:2022-07-24 13:06 Python 中的 replace() 函数有助于在用“new”子字符串替换“old”子字符串后返回原始字符串的副本。该函数还允许指定旧字符串需要替换的次数。

str.replace(old, new [, count]) # where old & new are strings

替换()参数:

replace() 函数接受三个参数。如果没有给定 count 参数,replace() 方法将用新的子字符串替换所有旧的子字符串。replace() 方法也可以与数字和符号一起使用。

参数 描述 必需/可选
old 要替换的旧子字符串 必需
new 将替换旧子串的新子串 可选
count 希望用新的子字符串替换旧的子字符串的次数 可选

替换()返回值

返回值始终是替换后的新字符串。此方法执行区分大小写的搜索。如果找不到指定的旧字符串,它将返回原始字符串。

输入 返回值
字符串 字符串(旧的替换为新的)

Python replace()方法的示例

示例 1: 如何在 Python 中使用 replace()

string = 'Hii,Hii how are you'
# replacing 'Hii' with 'friends'
print(string.replace('Hii', 'friends'))
string = 'Hii, Hii how are you, Hii how are you, Hii'
# replacing only two occurrences of 'Hii'
print(string.replace('Hii', "friends", 2)) 

输出:

friends,friends how are you
Hii, friends how are you, friends how are you, Hii

示例 Python 中 replace() 的工作原理

string = 'Hii,Hii how are you'
# returns copy of the original string because of count zero
print(string.replace('Hii', 'friends',0))
string = 'Hii, Hii how are you, Hii how are you, Hii'
# returns copy of the original string because old string not found
print(string.replace('fine', "friends", 2)) 

输出:

Hii,Hii how are you
Hii, Hii how are you, Hii how are you, Hii