Menu Close

Python String endswith() Method

Python String endswith() Method

In this article, you will learn about the Python string endswith() method to check a string end with a specific string or not. In the previous tutorial, we have seen the Python string count() method.

Python endswith() method:

Python endswith() method is a string method which is only working with string. Python endswith() method is used to return True if the string end with a specific character otherwise, return False.

Syntax:

The syntax of Python string endswith() is:-

string.endswith(suffix[, start[, end[[)

Parameters:

Python string endswith() method take three parameters:

suffix:- string or tuple of the suffix to be checked.
start:- ( Optional ) start parameter refer to the start position where suffix to be checked.
end:- ( Optional ) end parameter refer to the end position where suffix check e will end.

Return Value from endswith():

The Python string endswith function return Boolean value:

  • string endswith function return True if the string end with a specific string.
  • string endswith function return False if the string does not end with a specific string.

Python string endswith() Method Example:

Here we will take various example to understand string endswith function in Python.

Example 1:

Here we will use endswith() method without using start and end parameter.

str = "Programming Funda is the best place to learn to code."
print("Old string:- ", str)

str2 = str.endswith('learn coding.')

print(str2)
str2 = str.endswith('learn coding')
print(str2)

Output

Old string:-  Programming Funda is the best place to learn to code.
False
False

Example 2:

Here we will use endswith() method with using start and end parameter.

str = "Programming Funda is the best place to learn to code."
print("Old string:- ", str)

str2 = str.endswith('.', 0, 17)
print(str2)

str3 = str.endswith('.', 40, 50)
print(str3)

Output

Old string:-  Programming Funda is the best place to learn to code.
False
False

Example 3:

The Python string endswith function is also able to accept tuple suffix.

str = "Programming Funda is the best place to learn to code."

str2 = str.endswith(('Programming', 'Coding', '.'))
print(str2)

str3 = str.endswith(('Programming', 'Coding'))
print(str3)

Output

True
False

Conclusion:

In this tutorial, you have learned all about the Python string endswith() method to check a string ends with a specific string or not.
I hope this string method will help you. If you like this article, please comment and share it with your friends who want to learn Python programming from scratch to advanced.

For More Information:- Click Here

Python String count() Method
Python String expandtabs() Method

Was this post helpful?

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *