共計 670 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,replace() 方法用于替換字符串中的指定字符(或字符串)為另一個字符(或字符串)。
replace() 方法的語法如下:
string.replace(old, new[, count])
其中,string 是要進行替換操作的字符串,old 是要被替換的字符(或字符串),new 是用于替換的字符(或字符串),count 是可選參數,表示替換的次數(默認是全部替換)。
下面是 replace() 方法的示例:
string = "Hello, World!"
new_string = string.replace("World", "Alice")
print(new_string) # 輸出: Hello, Alice!
在上面的示例中,字符串 ”Hello, World!” 中的 ”World” 被替換為 ”Alice”,得到新的字符串 ”Hello, Alice!”。
需要注意的是,replace() 方法返回一個新的字符串,原始字符串不會被改變。如果要在原始字符串上進行替換操作,可以直接使用賦值語句將新的字符串賦給原始字符串變量。
另外,replace() 方法也可以用于刪除指定的字符(或字符串),只需要將 new 參數設置為空字符串即可。例如:
string = "Hello, World!"
new_string = string.replace("o", "") # 刪除字符串中的所有字母"o"
print(new_string) # 輸出: Hell, Wrld!
上面的示例中,字符串中的所有字母 ”o” 被替換為空字符串,得到新的字符串 ”Hell, Wrld!”。
丸趣 TV 網 – 提供最優質的資源集合!
正文完