当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python String replace()用法及代码示例


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

签名

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






相关用法


注:本文由纯净天空筛选整理自 Python String replace() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。