python 中的replace()
函數有助於在用“new”子字符串替換“old”子字符串後返回原始字符串的副本。該函數還允許指定舊字符串需要替換的次數。
**str.replace(old, new [, count]) ** #where old & new are strings
replace()
函數接受三個參數。如果沒有給定 count 參數,replace()
方法將用新的子字符串替換所有舊的子字符串。replace()
方法也可以與數字和符號一起使用。
參數 | 描述 | 必需/可選 |
---|---|---|
老的 | 要替換的舊子字符串 | 需要 |
新的 | 將替換舊子串的新子串 | 可選擇的 |
數數 | 希望用新的子字符串替換舊的子字符串的次數 | 可選擇的 |
返回值始終是替換後的新字符串。此方法執行區分大小寫的搜索。如果找不到指定的舊字符串,它將返回原始字符串。
| 投入 | 返回值 |
| 線 | 字符串(舊的替換為新的) |
string = 'Hii,Hii how are you'
# replacing 'Hii' with 'friends'
print(string.replace('Hii', 'friends'))
string = 'Hii, Hii how are you, Hii how are you, Hii'
# replacing only two occurences of 'Hii'
print(string.replace('Hii', "friends", 2))
輸出:
friends,friends how are you
Hii, friends how are you, friends how are you, Hii
string = 'Hii,Hii how are you'
# returns copy of the original string because of count zero
print(string.replace('Hii', 'friends',0))
string = 'Hii, Hii how are you, Hii how are you, Hii'
# returns copy of the original string because old string not found
print(string.replace('fine', "friends", 2))
輸出:
Hii,Hii how are you
Hii, Hii how are you, Hii how are you, Hii
原創文章,作者:GL33U,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/127017.html