Python 中的 replace(old, new [, max]

首页 / Python2入门教程 / Python 中的 replace(old, new [, max]

Python replace()返回字符串的副本,其中出现的old已被new替换,可以选择将替换次数限制为max。

replace - 语法

下面是Replace()方法-的语法

无涯教程网

str.replace(old, new[, max])
  • old    -  这是要替换的旧子字符串。

  • new   -  这是新的子字符串,它将替换旧的子字符串。

  • max   -  如果给定此可选参数max,则仅替换第一次计数。

replace - 返回值

此方法返回字符串的副本,其中所有出现的子字符串old替换为new。如果给定了可选参数max,则仅替换第一次出现的计数。

replace - 示例

下面的示例显示replace()方法的用法。

#!/usr/bin/python

str="this is string example....wow!!! this is really string"
print str.replace("is", "was")
print str.replace("is", "was", 3)

当无涯教程运行上面的程序时,它产生以下输出-

thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

深入剖析Kubernetes -〔张磊〕

MySQL实战45讲 -〔林晓斌〕

从0打造音视频直播系统 -〔李超〕

罗剑锋的C++实战笔记 -〔罗剑锋〕

手机摄影 -〔@随你们去〕

爆款文案修炼手册 -〔乐剑峰〕

朱涛 · Kotlin编程第一课 -〔朱涛〕

Vue 3 企业级项目实战课 -〔杨文坚〕

结构思考力 · 透过结构看问题解决 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)