Python String startswith
Now, we are going to learn about the startswith method. As the name of the method says, the startswith method helps us find if the given string starts with the specified string. This is like we are checking if the string ‘GyaniPandit’ starts with the string ‘Gyan’, and the method is going to return True or False, on the basis of whether or not the given string starts with the specified string. For example, the string ‘GyaniPandit’ startswith ‘Gyan’ and returns True. Let’s have a look at an example, which tries to demonstrate the same thing.
Python String startswith() Method
As you can see, in the above program, we have a string, and we are checking whether the given string starts with the specified string. In the above case, the output comes out to be True.
Now, Let’s say that we give such a string to the startswith method as an argument, such that the given string does not start with the given string argument. In such a situation, the output that we get is going to be False. Let’s have a look at the below program, which demonstrates the same thing.
As you can see in the above program, we have a string, and then we are trying to check if our string starts with the string ‘bye’. The answer to this question is simply False.
Also, we can provide the optional start and end arguments to the startswith method, through which we can specify the range to compare the string. Let’s have a look at the program, which demonstrates the same thing.
As you can see in the above program, we have a string, and then we are trying to call the startswith method. In that, we have passed the string as an argument, and then we have the optional start and end arguments. This is like starting comparing from the index 6, and checking if the string starts with the given string. The output in our case comes out to be True.
You can try and explore the startswith method, and we can use the method as and when required in our program. Remember that here, we can check if the string startswith the specified string. The method returns True or False, on the basis of whether or not, the string startswith the given string.