Check is a string starts with a particular substring in Python

In this post, we will learn to check is a string starts with a particular substring in Python?

Suppose a task of writing an essay is assigned with condition that it must start with a certain word. In such a case it is necessary to check whether the syntax starts with the provided word or not.

Python provides an inbuilt function startwith() which returns “True” if the string starts with a particular word otherwise returns “False”. If you are not getting the point, don’t worry we will understand it with examples in this tutorial.

Let’s begin the journey.

Also read: Check if a Key Exists in a JSON String or not in Python

 

With the help of inbuilt function startwith(), we will check is a string starts with a particular substring in Python or not.

content= "Welcome to the world of programming"
result=content.startswith("Welcome")
print(result)

In the above code a string “Welcome to the world of programming” is given and we want to check whether the string starts with the word “Welcome” or not. For this “Welcome” is passed as a parameter to the function startwith().

Output:

True

We can also check the substring at a specific index number passing the index number as an argument in the function.

# checking at a given index number.
# Is the string passed present at the given index number.

content="Welcome to the world of programming"
result=content.startswith("to",3)
print(result)

Output:

False

The substring “to” is not at index number 3, so the function returns the “False”.

That was the example of the beginning index number. The function also accept the end index number. If we provide the beginning and the end index number it checks the substring between those index numbers. If the substring is present it returns “True” else “False”.

#  Providing index of start and end

content="Welcome to the world of programming"
result=content.startswith("Welcome",0,10)
print(result)

Output:

True

I hope you understood it well. If you want to give any suggestions related to this post please comment below. For a tutorial on other Python topics comment below the topic name.

Also read: How to implement list as a stack in Python

Thank You.

Leave a Reply

Your email address will not be published. Required fields are marked *