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




startswith( ) FUNCTION


startswith( ) Function


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


Example :


x = "Hello Beautiful World"
if x.startswith("Hello"):
    print("The String starts with Hello")
else:
    print("The String does not start with Hello")


Output :



  The String starts with Hello

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' starts with the substring 'Hello'.


if x.startswith("Hello"):
    print("The String starts with Hello")
else:
    print("The String does not start with Hello")

And in this case the String, substring 'Hello Beautiful World' starts with the substring 'Hello'


And thus we get the below output.


The String starts with Hello

Now, let us say we have the below String,


"Hello World"

And we want to check if the above String starts with the substring 'World'.


Well ! Certainly the substring 'World' is not the substring that the above String starts with.


But we know that the substring 'World' starts from the position '6'.


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.startswith("World", 6, 11):
    print("The String starts with World from a specific position")
else:
    print("The String does not start with World")


Output :



  The String starts with World from 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' starts with the substring 'World'. And specified the range from 6 to 11 in the 'x.startswith("World", 6, 11)' function.


if x.startswith("World", 6, 11):
    print("The String starts with World from a specific position")
else:
    print("The String does not start with World")

java_Collections

And found that the substring 'World' starts from the location '6'.


So, we get the below output.


The String starts with World from a specific position