📜  Python string.replace()方法

📅  最后修改于: 2020-10-30 06:35:03             🧑  作者: Mango

Python字符串replace()方法

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

签名

replace(old, new[, count])

参量

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

new:新字符串,它将替换旧字符串。

count:处理替换的次数。

返回

返回字符串

让我们看一下replace()方法的一些示例,以了解其功能。

Python字符串replace()方法示例1

# 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()方法示例2

# 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()方法示例3

# 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