Python 字串 endswith() 方法



Python 字串endswith()方法檢查輸入字串是否以指定的suffix結尾。如果字串以指定的suffix結尾,則此函式返回True,否則返回False。

此函式具有一個必需引數和兩個可選引數。必需引數是要檢查的字串,可選引數是起始和結束索引。預設情況下,起始索引為0,結束索引為length -1。

在下一節中,我們將學習更多關於Python字串endswith()方法的詳細資訊。

語法

以下是Python字串endswith()方法的語法。

str.endswith(suffix[, start[, end]])

引數

Python字串endswith()方法的引數如下所示。

  • suffix − 此引數指定要查詢的字串或字尾元組。

  • start − 此引數指定搜尋的起始索引。

  • end − 此引數指定搜尋結束的結束索引。

返回值

如果字串以指定的suffix結尾,則Python字串endswith()方法返回True,否則返回False。

示例

將Python字串endswith()方法應用於帶有suffix作為引數的字串將返回一個布林值True,如果字串以該suffix結尾。否則,它返回False。

以下是一個示例,其中建立了一個字串“Hello!Welcome to Tutorialspoint.”,並且還指定了suffix 'oint'。然後,在字串上呼叫endswith()函式,只使用suffix作為其引數,並使用print()函式將結果列印為輸出。

str = "Hello!Welcome to Tutorialspoint.";
suffix = "oint.";
result=str.endswith(suffix)
print("The input string ends with the given suffix:", result)

執行上述程式後,將生成以下輸出 -

The input string ends with the given suffix: True

示例

將Python字串endswith()方法應用於帶有suffix、起始索引作為引數的字串將返回一個布林值True,如果字串以該suffix結尾並從指定的起始索引開始。否則,它返回False。

以下是一個示例,其中建立了一個字串“Hello!Welcome to Tutorialspoint.”,並且還指定了suffix 'oint'。然後,在字串上呼叫endswith()函式,傳遞suffix和起始索引'28'作為其引數,並使用print()函式將結果列印為輸出。

str = "Hello!Welcome to Tutorialspoint.";
suffix = "oint.";
result=str.endswith(suffix, 28)
print("The input string ends with the given suffix:",result)

執行上述程式後獲得的輸出如下所示 -

The input string ends with the given suffix: False

示例

將Python字串endswith()方法應用於帶有suffix、起始索引和結束索引作為引數的字串將返回一個布林值True,如果字串在給定範圍內以該suffix結尾。否則,它返回False。

以下是一個示例,其中建立了一個字串“Hello!Welcome to Tutorialspoint.”,並且還指定了suffix 'oint.'。然後,在字串上呼叫endswith()函式,傳遞suffix、起始索引'27'和結束索引'32'作為其引數,並使用print()函式將結果列印為輸出。

str = "Hello!Welcome to Tutorialspoint.";
suffix = "oint.";
result=str.endswith(suffix, 27, 32)
print("The input string ends with the given suffix:",result)

執行上述程式後,將顯示以下輸出 -

The input string ends with the given suffix: True

示例

Python字串的endswith()方法的第一個引數必須是字串形式,指定要在輸入字串中檢查的字尾。如果引數中未指定字串,則會發生型別錯誤。

下面是一個示例,其中建立了一個字串"Hello!Welcome to Tutorialspoint.",然後在該字串上呼叫endswith()函式,並將起始索引'27'和結束索引'32'作為引數傳遞,最後使用print()函式將結果列印輸出。

str = "Hello!Welcome to Tutorialspoint.";
result=str.endswith(27, 32)
print("The input string ends with the given suffix:",result)

執行上述程式後顯示的輸出如下:

Traceback (most recent call last):
  File "main.py", line 2, in 
    result=str.endswith(27, 32)
TypeError: endswith first arg must be str or a tuple of str, not int

示例

Python字串endswith方法至少需要一個引數。如果沒有指定引數,則會發生型別錯誤。

下面是一個示例,其中建立了一個字串"Hello!Welcome to Tutorialspoint.",然後在該字串上呼叫endswith()函式,不傳遞任何引數,最後使用print()函式將結果列印輸出。

str = "Hello!Welcome to Tutorialspoint.";
result=str.endswith()
print("The input string ends with the given suffix:",result)

上述程式的輸出如下所示:

Traceback (most recent call last):
  File "main.py", line 2, in 
    result=str.endswith()
TypeError: endswith() takes at least 1 argument (0 given)
python_strings.htm
廣告