Python 中的 replace() 函数有助于返回原始字符串的副本,替换“旧”子字符串为“新”子字符串。该函数还允许指定旧字符串需要替换的次数。
str.replace(old, new [, count]) #where old & new are strings
replace() 函数接受三个参数。如果未提供 count 参数,则 replace() 方法将替换所有旧子字符串为新子字符串。replace() 方法也可以与数字和符号一起使用。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 旧 | 您要替换的旧子字符串 | 必需 |
| new | 将替换旧子字符串的新子字符串 | 可选 |
| 计数 | 您希望用新子字符串替换旧子字符串的次数 | 可选 |
返回值始终是替换后的新字符串。此方法执行区分大小写的搜索。如果未找到指定的旧字符串,它将返回原始字符串。
| 输入 | 返回值 |
|---|---|
| 字符串 | 字符串(旧的替换为新的) |
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 occurences of 'Hii'
print(string.replace('Hii', "friends", 2))
输出
friends,friends how are you Hii, friends how are you, friends how are you, Hii
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