Python endswith method returns Boolean TRUE if the string ends with the specified substring. Otherwise, it returns False. The endswith Function is very useful when we want to check the ending term of User inputs, and the basic syntax of it is
String_Value.endswith(Substring, Starting_Position, Ending_Position)
- Substring: String you want to search for.
- Starting_Position: If you want to specify the starting index position, Please specify the index value here.
- Ending_Position: If you want to specify the Ending index position, Please specify the index value here.
Python endswith method Example
The following set of examples help you understand the endswith Function. First, we declared a sample text. Next, Str2 checks whether the string Str1 ended with the term ‘Gateway’ or not and prints the output.
It also allows us to use directly on a string literal. So, we used the same for Str3.
The Python string endswith function allows us to use beginning and ending indices. By specifying the starting and ending index positions, we can increase performance.
The following Python statement for Str5 starts looking from position 6 and checks whether the keyword ‘Python’ is at position 12 or not.
If it does not find the specified string at the ending point, it returns Boolean False. The following Str7 statement is returning False because this String Method starts looking for the term ‘Python’, and we all know that Str1 is ending with ‘Gateway’.
Str1 = 'Learn Python at Tutorial Gateway'; Str2 = Str1.endswith('Gateway') print('First Output of a method is = ', Str2) Str3 = 'Find Tutorial at Tutorial Gateway'.endswith('Gateway') print('Second Output of a method is = ', Str3) # Using First Index Str5 = Str1.endswith('Python', 6, 12) print('Third Output of a method is = ', Str5) # Searching for Non existing Str7 = Str1.endswith('Python') print('Fourth Output of a method is = ', Str7)