The endswith() Function is used to check, if a String ends with a particular substring.
x = "Hello Beautiful World" if x.endswith("World"): print("The String ends with World") else: print("The String does not end with World")
In the above code, we have declared a String 'Hello Beautiful World' and assigned it to a variable 'x'.
And we have checked if the String, 'Hello Beautiful World' ends with the substring 'World'.
if x.endswith("World"): print("The String ends with World") else: print("The String does not end with World")
And in this case the String, substring 'Hello Beautiful World' ends with the substring 'World'
And thus we get the below output.
Now, let us say we have the below String,
And we want to check if the above String ends with the substring 'Hello'.
Well! Certainly the substring 'Hello' is not the substring that the above String ends with.
But we know that the substring 'Hello' starts from the position '0' and ends at position '4'.
And luckily, Python provides a second and third parameter that specifies the range.
Let us see with the below example.
x = "Hello World" if x.endswith("Hello", 0, 5): print("The String ends with Hello at a specific position") else: print("The String does not end with Hello")
In the above code, we have declared a String 'Hello World' and assigned it to a variable 'x'.
And we have checked if the String, 'Hello World' ends with the substring 'Hello'. And specified the range from 0 to 5 in the 'x.endswith("Hello", 0, 5)' function.
if x.endswith("Hello", 0, 5): print("The String ends with Hello at a specific position") else: print("The String does not end with Hello")
And found that the substring 'Hello' ends at position 4. We just add '1' to it and make the range as '5'
So, we get the below output.