一、replace方法介紹
在Python中,字符串是一種不可變序列,這就意味着一旦字符串被創建,它的值就不能再次改變。但是,我們可以使用replace方法來對字符串進行替換操作。
replace方法的語法如下:
str.replace(old, new[, count])
其中,old表示要被替換的子串,new表示用來替換的子串,count表示替換的次數。如果不指定count,則默認替換所有出現的子串。
二、替換單個子串
在處理字符串時,經常需要將某個子串替換成另一個子串。例如,將字符串中的”hello”替換成”hi”:
str = "hello world" new_str = str.replace("hello", "hi") print(new_str)
輸出結果為:”hi world”。
三、替換多個子串
有時候我們需要同時替換字符串中的多個子串。可以調用多次replace方法,也可以將多個子串用字典表示,然後使用字符串的format方法進行替換。
方法一:
str = "It's sunny today. I like to swim." new_str = str.replace("sunny", "cloudy").replace("swim", "stay inside") print(new_str)
輸出結果為:”It’s cloudy today. I like to stay inside.”
方法二:
str = "It's sunny today. I like to swim." mapping = {"sunny": "cloudy", "swim": "stay inside"} new_str = str.format(**mapping) print(new_str)
輸出結果與方法一相同。
四、不替換首尾子串
有時候需要替換一個子串,但是這個子串只能在某個位置出現,比如只能位於字符串的中間,不能出現在字符串的首尾。可以使用正則表達式來實現這個功能。
import re str = "I love python, python is my favorite language." pattern = "(?<!^)python(?!$)" new_str = re.sub(pattern, "Java", str) print(new_str)
輸出結果為:”I love Java, Java is my favorite language.”
五、使用replace方法時需要注意的問題
- replace方法返回新的字符串,不會改變原有字符串的值。
- replace方法區分大小寫。
- 當替換的子串與原有字符串完全匹配時,replace方法會返回新的字符串,否則返回原字符串。
- replace方法只能替換字符串中的子串,不能替換整個字符串。
- 當替換的子串中包含轉義字符時,需要將轉義字符進行轉義。例如,需要將”\n”替換成空格:
str = "hello\nworld" new_str = str.replace("\n", " ") print(new_str)
輸出結果為:”hello world”。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/293767.html