教育行業(yè)A股IPO第一股(股票代碼 003032)

全國咨詢/投訴熱線:400-618-4000

如何用Python進(jìn)行查詢和替換一個文本字符串?

更新時間:2023年02月28日11時30分 來源:傳智教育 瀏覽次數(shù):

好口碑IT培訓(xùn)

  您可以使用Python內(nèi)置的字符串方法或正則表達(dá)式來查詢和替換一個文本字符串。下面是一些示例代碼:

  使用字符串方法

string = "Hello, world!"
substring = "world"
replacement = "Python"
new_string = string.replace(substring, replacement)
print(new_string)
# 輸出:Hello, Python!

  在上面的代碼中,我們使用了字符串的 replace() 方法,將子字符串 "world" 替換為 "Python"。

  使用正則表達(dá)式

import re

string = "Hello, world!"
pattern = r"world"
replacement = "Python"
new_string = re.sub(pattern, replacement, string)
print(new_string)
# 輸出:Hello, Python!

  在上面的代碼中,我們使用了 re 模塊的 sub() 函數(shù),將模式字符串 "world" 替換為 "Python"。該函數(shù)會搜索整個字符串并將所有匹配的子字符串替換為指定的字符串。

0 分享到:
和我們在線交談!