Python removeprefix() 方法



Python 字串removeprefix() 方法用於從字串開頭移除指定的字首。

如果字串以指定的字首開頭,則該方法會從字串中移除字首並返回修改後的字串。如果字串沒有以指定的字首開頭,則該方法會返回原始字串,保持不變。

語法

以下是 Python 字串 removeprefix() 方法的基本語法:

string.removeprefix(prefix)

引數

此方法接受一個字串作為引數,該字串指定要從字串開頭移除的字首。

返回值

該方法返回一個新的字串,其中從開頭移除了指定的字首。

示例

在以下示例中,我們使用 removeprefix() 方法從字串 "text" 中移除字首 "Hello ":

text = "Hello World"
result = text.removeprefix("Hello ")
print(result)    

輸出

獲得的輸出如下:

World

示例

此示例顯示,如果給定的字首在指定的字串中不存在,則返回原始字串,沒有任何修改:

text = "World"
result = text.removeprefix("Hello ")
print(result)      

輸出

以上程式碼的輸出如下:

World

示例

removeprefix() 方法預設執行區分大小寫的移除。在此例項中,該方法不會從字串 "text" 中移除字首 "hello ",而是返回原始字串:

text = "HELLO World"
result = text.removeprefix("hello ")
print(result) 

輸出

產生的結果如下所示:

HELLO World

示例

現在,我們從字串 "text" 中移除數字字首 "12345":

text = "12345World"
result = text.removeprefix("12345")
print(result)

輸出

我們得到如下所示的輸出:

World
split_and_join.htm
廣告