
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if String Starts with Substring in Python
In this article we are going to check whether the string starts with the substring or not, It is useful for checking whether the string starts with the substring, which is helpful in tasks like filtering data or validating input.
In Python there are various ways to perform this check, such as startswith(), string slicing and regular expression. Let's dive into the article to learn more about them.
Using python startswith() Method
The Python startswith() method is used to check whether the string starts with a given substring or not. This method accepts a prefix string that you want to search for and is invoked on a string object.
This method return true if the string starts with the specified value, or else it returns false.
Syntax
Following is the syntax of python startswith() method ?
str.startswith(value, start, end)
Example 1
Let's look at the following example, where we are going to consider the basic usage of the startswith() method.
str1 = "Welcome to Tutorialspoint" substr = "Wel" print(str1.startswith(substr))
Output
Output of the above program is as follows ?
True
Example 2
Consider another scenario, where we are going to use the substring that is not part of the string and observe the output.
str1 = "Ciaz Audi BMW" substr = "RX100" print(str1.startswith(substr))
Output
Output of the above program is as follows ?
False
Using python re Module
The python re module supports for the regular expressions, helping in string patterns matching and manipulation. It includes functions like match(), search() to identify, extract or replace patterns in strings.
Example 1
In the following example, we are going to use the re.search() to check whether the string starts with substring or not.
import re str1 = "Welcome to Tutorialspoint" substr = "Wel" print(bool(re.search(substr, str1)))
Output
Following is the output of the above program ?
True
Example 2
Following is the example, where we are going to use the re.match() to check whether the string starts with substring or not.
import re x = "Welcome Everyone" y = "Wel" z = bool(re.match(y, x)) print(z)
Output
Following is the output of the above program ?
True