Python 字符串 replace()

replace() 方法用另一个字符串替换子字符串的每个匹配项。

示例

text = 'bat ball'

# replace 'ba' with 'ro' replaced_text = text.replace('ba', 'ro')
print(replaced_text) # Output: rot roll

replace() 语法

其语法为

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

replace() 参数

replace() 方法最多可接受三个参数

  • old - 我们要替换的旧子字符串
  • new - 将替换旧子字符串的新子字符串
  • count(可选)- 您要用字符串替换子字符串的次数

注意:如果未指定count,则 replace() 方法将所有子字符串的出现替换为字符串。


replace() 返回值

replace() 方法返回字符串的副本,其中子字符串被字符串替换。原始字符串保持不变。

如果未找到子字符串,则返回原始字符串的副本。


示例 1:使用 replace()

song = 'cold, cold heart'

# replacing 'cold' with 'hurt' print(song.replace('cold', 'hurt'))
song = 'Let it be, let it be, let it be, let it be'
# replacing only two occurrences of 'let' print(song.replace('let', "don't let", 2))

输出

hurt, hurt heart
Let it be, don't let it be, don't let it be, let it be

更多字符串 replace() 示例

song = 'cold, cold heart'
replaced_song = song.replace('o', 'e')
# The original string is unchanged print('Original string:', song) print('Replaced string:', replaced_song) song = 'let it be, let it be, let it be' # maximum of 0 substring is replaced # returns copy of the original string
print(song.replace('let', 'so', 0))

输出

Original string: cold, cold heart
Replaced string: celd, celd heart
let it be, let it be, let it be

另请阅读

在结束之前,让我们测试一下您对 Python 字符串 replace() 的知识!您能解决以下挑战吗?

挑战

编写一个函数,将字符串中所有出现的 ':)' 替换为笑脸表情符号。

  • 定义一个函数,将字符串作为输入。
  • 在函数内部,使用 replace 方法将所有出现的 ':)' 替换为笑脸表情符号。
  • 返回修改后的字符串。
  • 例如,输入 'Hello :) How are you :) ?',输出应为 'Hello 😊 How are you 😊 ?'
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战