共計 510 個字符,預計需要花費 2 分鐘才能閱讀完成。
Python 中可以使用 str.replace()
方法來實現一鍵替換。該方法用于將字符串中的指定子字符串替換為另一個子字符串。其語法如下:
new_string = old_string.replace(old_substring, new_substring)
其中,old_string
是原始字符串,old_substring
是需要替換的子字符串,new_substring
是替換后的子字符串。調用 replace()
方法后,會返回一個新的字符串 new_string
,其中所有的old_substring
都被替換為 new_substring
。
以下是一個示例:
sentence = "I love apples. Apples are delicious."
new_sentence = sentence.replace("apples", "oranges")
print(new_sentence)
輸出結果為:
I love oranges. Oranges are delicious.
在上述示例中,原始字符串 sentence
中的所有 ”apples” 都被替換為 ”oranges”,并存儲在新的字符串 new_sentence
中。
丸趣 TV 網 – 提供最優質的資源集合!
正文完