首頁  >  文章  >  後端開發  >  python如何替換字串的內容

python如何替換字串的內容

WBOY
WBOY轉載
2024-03-01 22:55:02814瀏覽

python如何替換字串的內容

python中可以使用replace()函數來取代字串的內容。 replace()函數接受兩個參數,第一個參數是要被替換的字串,第二個參數是要替換成的字串。範例如下:

string = "Hello, World!"
new_string = string.replace("World", "Python")
print(new_string)

輸出結果為:

Hello, Python!

注意,replace()函數傳回的是替換後的新字串,原始字串不會被修改。如果想要在原始字串上進行替換,可以直接賦值給原始字串變數。例如:

string = "Hello, World!"
string = string.replace("World", "Python")
print(string)

輸出結果為:

Hello, Python!

以上是python如何替換字串的內容的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:lsjlt.com。如有侵權,請聯絡admin@php.cn刪除