Python 字符串 replace()方法

Python 字符串 replace()方法

返回一个字符串的副本,其中所有出现的子字符串old都被new替代。如果给定了可选参数count,那么只会替换第一个count个出现的子字符串。

语法:

replace(old, new[, count])

参数

old: 在这里,该参数用于被替换的旧字符串。

new: 在这里,该参数用于替换旧字符串的新字符串。

count: count 参数用于描述替换操作的次数。

返回值

返回字符串。

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

示例1

# Here, we are creating a simple python program to understand the replace() method # with the examples  
# Here, we are creating a Variable and declaration it with some data  
str = "Java is a programming language"  
# Here, we are calling the function  
str2 = str.replace("Java","C")  
# Here, we are declaring another variable str2 and storing the string after performing 
# replace() method
# Here, we are displaying the result  
print("The Old String before performing the replace method is: \n",str)  
print("The new String after performing the replace method is:  \n",str2)  

输出:

The Old String before performing the replace method is: 
 Java is a programming language
The new String after performing the replace method is:  
 C is a programming language

示例2

# Here, we are creating a simple python program to understand the replace() method # with the examples  
# Here, we are creating a Variable and declaration it with some data  
str = "Java C C# Java Php Python Java"  
# Here, we are calling the function and replacing all the occurrence of the old string  
str2 = str.replace("Java","C#")  
# Here, we are declaring another variable str2 and storing the string after performing 
# replace() method
# Here, we are displaying the result  
print("The Old String before performing the replace method is: \n",str)  
print("The new String after performing the replace method is:  \n",str2) 
# Here, we are calling the function and replacing all the first occurrence of the old  
# string  
str2 = str.replace("Java","C#", 1)  
# Here, we are declaring another variable str2 and storing the string after performing 
# replace() method
# Here, we are displaying the result  
print("The Old String before performing the replace method is: \n",str)  
print("The new String after performing the replace method is:  \n",str2)  

输出:

Old String: 
The Old String before performing the replace method is: 
 Java C C# Java Php Python Java
The new String after performing the replace method is:  
 C# C C# C# Php Python C#

 The Old String before performing the replace method is:  
 Java C C# Java Php Python Java
The new String after performing the replace method is: 
 C# C C# Java Php Python Java

示例3

# Simple Python program to understand the replace() method with example  
# Variable declaration  
str = "Apple is a fruit"  
# Here, we are calling the function  
str2 = str.replace(str,"Tomato is also a fruit")  
# Here, we are displaying the result  
print(str2)  

输出:

Tomato is also a fruit

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程