Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




endswith( ) FUNCTION


endswith( ) Function


The endswith() Function is used to check, if a String ends with a particular substring.


Example :


x = "Hello Beautiful World"
if x.endswith("World"):
    print("The String ends with World")
else:
    print("The String does not end with World")


Output :



  The String ends with World

In the above code, we have declared a String 'Hello Beautiful World' and assigned it to a variable 'x'.


x = "Hello Beautiful World"

java_Collections

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.


The String ends with World

Now, let us say we have the below String,


"Hello World"

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'.


java_Collections

And luckily, Python provides a second and third parameter that specifies the range.


Let us see with the below example.


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")


Output :



  The String ends with Hello at a specific position

In the above code, we have declared a String 'Hello World' and assigned it to a variable 'x'.


x = "Hello World"

java_Collections

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")

java_Collections

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.


The String ends with Hello at a specific position