Python3 中的 replace(old,new[,count]

首页 / Python3入门教程 / Python3 中的 replace(old,new[,count]

返回字符串的副本,其中所有出现的子字符串old被new替换。如果给出了可选的参数count,则仅替换第一个出现的计数。

replace - 语法

replace(old, new[, count])

replace - 参数

old       -  将被替换的旧字符串。

new     - 新字符串将替换旧字符串。

count  - 处理替换的次数。

replace - 返回

返回字符串

无涯教程来看一些 replace()方法的示例,以了解其功能。

# Python replace() method example
# 变量声明
str = "Java is a programming language"
# 调用函数
str2 = str.replace("Java","C")
# 显示结果
print("Old String: \n",str)
print("New String: \n",str2)

输出

Old String: 
 Java is a programming language
New String: 
 C is a programming language
replace - Python字符串replace()方法示例2
# Python replace() method example
# 变量声明
str = "Java C C# Java Php Python Java"
# 调用函数
str2 = str.replace("Java","C#") # replaces all the occurences
# 显示结果
print("Old String: \n",str)
print("New String: \n",str2)
# 调用函数
str2 = str.replace("Java","C#",1) # replaces first occurance only
# 调用函数
print("\n Old String: \n",str)
print("New String: \n",str2)

输出

Old String: 
 Java C C# Java Php Python Java
New String: 
 C# C C# C# Php Python C#

 Old String: 
 Java C C# Java Php Python Java
New String: 
 C# C C# Java Php Python Java
replace - Python字符串replace()方法示例3
# Python replace() method example
# 变量声明
str = "Apple is a fruit"
# 调用函数
str2 = str.replace(str,"Tomato is also a fruit")
# 显示结果
print(str2)

输出

Tomato is also a fruit

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

技术教程推荐

程序员进阶攻略 -〔胡峰〕

Go语言从入门到实战 -〔蔡超〕

Electron开发实战 -〔邓耀龙〕

性能优化高手课 -〔尉刚强〕

说透芯片 -〔邵巍〕

零基础实战机器学习 -〔黄佳〕

手把手带你搭建秒杀系统 -〔佘志东〕

郭东白的架构课 -〔郭东白〕

Web漏洞挖掘实战 -〔王昊天〕

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