4.6.1 replace函数

更新于 2026年10月13日 版权声明
4.6.1 replace函数

(1)描述

返回字符串中的 old(旧字符串) 替换成new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。

(2)语法

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

参数:

old——将被替换的子字符串。(https://www.daowen.com)

new——新字符串,用于替换old子字符串。

max——可选字符串,替换不超过 max 次。

(3)快速体验

mystr = "hello world and hbes and hbeszy and Python"
# 结果:hello world he hbes he hbeszy he Python
print(mystr.replace('and', 'he'))
# 结果:hello world he hbes and hbeszy and Python
print(mystr.replace('and', 'he', 1)) #替换不超过 1 次
# 结果:hello world and hbes and hbeszy and Python
print(mystr)

✍AI写作