replace 函數(shù)用于替換字符串中的指定子串,它有以下用法:直接替換:使用指定子串替換另一個(gè)指定子串。使用正則表達(dá)式:使用正則表達(dá)式進(jìn)行模式匹配和替換。替換所有匹配項(xiàng):使用 count 參數(shù)指定替換所有匹配項(xiàng)。替換沒有匹配項(xiàng):如果子串不在字符串中,則返回原始字符串。replace 函數(shù)不會(huì)修改原始字符串,只返回一個(gè)替換后的新字符串。
replace 函數(shù)的使用方法
replace 函數(shù)在 Python 中用于替換字符串中的指定子串。它接受三個(gè)參數(shù):
- 要搜索的子串
- 要替換的字符串
- 要執(zhí)行替換的操作的對(duì)象
語法:
复制代码
- replace(old, new, String)
參數(shù):
- old:要搜索的子串
- new:要替換的字符串
- string:要執(zhí)行替換操作的字符串
返回值:
返回一個(gè)替換后的新字符串。
用法:
- 直接替換:
复制代码
- my_string = "Hello, world!" new_string = my_string.replace("world", "Python")
輸出:
复制代码
- Hello, Python!
- 使用正則表達(dá)式:
replace 函數(shù)還支持使用正則表達(dá)式進(jìn)行模式匹配和替換。
复制代码
- import re my_string = "123_456_789" new_string = re.sub(r"_", "", my_string)
輸出:
复制代码
- 123456789
- 替換所有匹配項(xiàng):
默認(rèn)情況下,replace 函數(shù)只替換第一個(gè)匹配項(xiàng)。要替換所有匹配項(xiàng),可以使用 count 參數(shù):
复制代码
- my_string = "Hello, world! Hello, world!" new_string = my_string.replace("world", "Python", 1) # 替換第一個(gè)匹配項(xiàng) new_string2 = my_string.replace("world", "Python", 2) # 替換兩個(gè)匹配項(xiàng)
輸出:
复制代码
- Hello, Python! Hello, world! Hello, Python! Hello, Python!
- 替換沒有匹配項(xiàng):
如果要搜索的子串不在目標(biāo)字符串中,replace 函數(shù)將返回原始字符串。
注意:
replace 函數(shù)不會(huì)修改原始字符串。它只返回一個(gè)替換后的新字符串。