startswith( ) Function
The startswith( ) Function is used to check, if a String begins with a particular substring.
x = "Hello Beautiful World" if x.startswith("Hello"): print("The String starts with Hello") else: print("The String does not start with Hello")
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' 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.
Now, let us say we have the below String,
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'.
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.startswith("World", 6, 11): print("The String starts with World from a specific position") else: print("The String does not start with World")
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' 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")
And found that the substring 'World' starts from the location '6'.
So, we get the below output.