Tutorial Study Image

Python endswith()

The endswith() function in python helps to check whether a string end with a given suffix. If yes the function returns true else false.


str.endswith(suffix[, start[, end]]) #where index is an integer value
 

endswith() Parameters:

The endswith() function takes three parameters. If the starting and ending prefix is not specified, then by default it will check the whole string starting from zero indexes.

Parameter Description Required / Optional
suffix String or tuple of suffixes to be checked Required
start Starting position where suffix is to be checked within the string optional
end  Ending position where suffix is to be checked within the string optional

endswith() Return Value

The return value is always a boolean value. It is also possible to pass tuple suffixes to this method. If the string end with any element of the tuple this function returns true.

Input Return Value
 if strings end with the specified suffix True
if string doesn't end with the specified suffix False

Examples of endswith() method in Python

Example 1: How endswith() works without start and end parameters?


string = "Hii, How are you?"

result = string.endswith('are you')
# returns False
print(result)

result = string.endswith('are you?')
# returns True
print(result)

result = string.endswith('Hii, How are you?')
# returns True
print(result)
 

Output:


False
True
True

Example 2: How endswith() works with start and end parameters?


string = "Hii, How are you?"

# start parameter: 10

result = string.endswith('you?', 10)
print(result)

# Both start and end is provided

result = string.endswith('are?', 2, 8)
# Returns False
print(result)

result = string.endswith('you?', 10, 16)
# returns True
print(result)
 

Output:


True
False
True

Example 3: How endswith() works with tuple suffix?


string = "apple is a fruit"
result = string.endswith(('apple', 'flower'))

# prints False
print(result)

result = string.endswith(('apple', 'fruit', 'grapes'))
#prints True
print(result)

# With start and end parameter
result = string.endswith(('is', 'to'), 0, 8)

# prints True
print(result)
 

Output:


True
False
True