共計 406 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,可以使用 replace() 方法來替換字符串中的指定子字符串。replace()方法的語法如下:
str.replace(old, new, count)
其中,old是要被替換的子字符串,new是用來替換的新字符串,count是可選參數(shù),用于指定替換的次數(shù)。如果不指定 count 參數(shù),則所有匹配的子字符串都會被替換。
示例代碼如下:
str = "Hello, World!"
new_str = str.replace("Hello", "Hi")
print(new_str) # 輸出: Hi, World!
如果想要替換所有匹配的子字符串,可以不指定 count 參數(shù):
str = "apple, apple, orange, apple"
new_str = str.replace("apple", "banana")
print(new_str) # 輸出: banana, banana, orange, banana
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完