Python 3 – 字符串替換(replace)方法
Python 3 中的字符串是不可變的,也就是說(shuō)一旦創(chuàng)建,它們不能被改變。愛掏網(wǎng) - it200.com但是我們可以對(duì)字符串進(jìn)行各種操作,例如獲取子字符串、合并字符串、復(fù)制字符串等等。愛掏網(wǎng) - it200.com其中非常常見的操作就是字符串替換。愛掏網(wǎng) - it200.com
在 Python 3 中,我們可以使用字符串的 replace()
方法,替換字符串中的子字符串。愛掏網(wǎng) - it200.com這個(gè)方法的語(yǔ)法是非常簡(jiǎn)單的:
str.replace(old, new[, count])
其中:
str
是要進(jìn)行替換操作的字符串;old
是要被替換的子字符串;new
是替換的新字符串;count
是可選的參數(shù),指定替換的次數(shù)。愛掏網(wǎng) - it200.com
如果 count
沒有被指定,默認(rèn)情況下會(huì)替換所有匹配的子字符串。愛掏網(wǎng) - it200.com
下面我們來(lái)看幾個(gè)例子。愛掏網(wǎng) - it200.com
我們首先來(lái)看一個(gè)簡(jiǎn)單的字符串替換的例子:
text = "Hello, World!"
new_text = text.replace("World", "Python")
print(new_text)
運(yùn)行上面的代碼會(huì)輸出:
Hello, Python!
這個(gè)例子中,我們把字符串 "World"
替換成了 "Python"
。愛掏網(wǎng) - it200.com
示例2 – 替換指定次數(shù)
我們可以通過(guò)指定 count
參數(shù)來(lái)限制替換的次數(shù)。愛掏網(wǎng) - it200.com例如:
text = "one two three four three three three"
new_text = text.replace("three", "3", 2)
print(new_text)
運(yùn)行上面的代碼會(huì)輸出:
one two 3 four 3 three three
這個(gè)例子中,我們把字符串 "three"
替換成了 "3"
,但是只替換了前兩個(gè)匹配。愛掏網(wǎng) - it200.com
示例3 – 多個(gè)替換
我們甚至可以一次性把多個(gè)子字符串替換為指定的新字符串。愛掏網(wǎng) - it200.com例如:
text = "one two three four three three three"
new_text = text.replace("one", "1").replace("two", "2")\
.replace("three", "3").replace("four", "4")
print(new_text)
運(yùn)行上面的代碼會(huì)輸出:
1 2 3 4 3 3 3
這個(gè)例子中,我們先用 replace()
把字符串中的 "one"
替換成 "1"
,再用 replace()
把 "two"
替換成 "2"
,以此類推。愛掏網(wǎng) - it200.com這樣就能一次性把多個(gè)子字符串替換為指定的新字符串了。愛掏網(wǎng) - it200.com
示例4 – 復(fù)雜替換
有些時(shí)候,我們可能需要進(jìn)行一些復(fù)雜的字符串替換操作。愛掏網(wǎng) - it200.com例如,我們要把一個(gè)字符串中包含的 URL 都替換成超鏈接。愛掏網(wǎng) - it200.com這個(gè)時(shí)候,我們可以使用正則表達(dá)式來(lái)匹配子字符串,并使用一個(gè)函數(shù)來(lái)生成替換的新字符串。愛掏網(wǎng) - it200.com示例如下: