无涯教程-Python3 - replace(old,new[,count])函数

79 阅读1分钟

返回字符串的副本,其中所有出现的子字符串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

参考链接

www.learnfk.com/python3/pyt…