當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。