📅  最后修改于: 2020-10-30 06:35:03             🧑  作者: Mango
返回该字符串的副本,其中所有出现的子字符串old都替换为new。如果给出了可选的参数count,则仅替换第一个出现的计数。
replace(old, new[, count])
old:将被替换的旧字符串。
new:新字符串,它将替换旧字符串。
count:处理替换的次数。
返回字符串
让我们看一下replace()方法的一些示例,以了解其功能。
# Python replace() method example
# Variable declaration
str = "Java is a programming language"
# Calling function
str2 = str.replace("Java","C")
# Displaying result
print("Old String: \n",str)
print("New String: \n",str2)
输出:
Old String:
Java is a programming language
New String:
C is a programming language
# Python replace() method example
# Variable declaration
str = "Java C C# Java Php Python Java"
# Calling function
str2 = str.replace("Java","C#") # replaces all the occurences
# Displaying result
print("Old String: \n",str)
print("New String: \n",str2)
# Calling function
str2 = str.replace("Java","C#",1) # replaces first occurance only
# Displaying result
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
# Python replace() method example
# Variable declaration
str = "Apple is a fruit"
# calling function
str2 = str.replace(str,"Tomato is also a fruit")
# displaying result
print(str2)
输出:
Tomato is also a fruit