String starts with substring python

Python String startswith: Check if String Starts With Substring

Python String startswith Check if String Starts With Substring Cover Image

The Python startswith method is used to check if a string starts with a specific substring. In this tutorial, you’ll learn how to use the Python startswith function to evaluate whether a string starts with one or more substrings. Being able to check if a string starts with another string is a useful way to check user input, such as for phone numbers or names. Alternatively, you can use the startswithmethod to check if a string ends with a substring.

By the end of this tutorial, you’ll have learned:

  • How to use the Python startswith() function to check if a string starts with a substring
  • How to use the Python startswith() function with multiple strings
  • How to use the Python startswith() function without case sensitivity
  • How to use the Python startswith() function with a list of strings

Understanding the Python startswith Function

Before diving into how to use the Python startswith() function, it’s essential to understand the syntax of the function. The code block below breaks down the different required and optional parameters that the function has to offer.

# Understanding the Python startswith() Function str.startswith(prefix, start, end)

The table below breaks down the parameters of the function as well as any default arguments that the function provides:

Источник

Check if a string starts with a substring in Python

In this Python tutorial, we wil learn about some methods using which we can check whether a string starts with a substring or not.

Table Of Contents

Introduction

Suppose we have a string and a substring,

exampleStr = 'MSD is the Best Finisher, MSD is the only captain to win all the icc trophies of white ball cricket.' subStr = "MSD"

Now we want to check if the string starts with the given substring or not. Like in above example, the string exampleStr starts with the substrig subStr i.e. “MSD”.

There are different ways to achieve this. Let’s discuss them one by one.

Frequently Asked:

Check if a string starts with a substring using startswith() function:

First method that we will be using is the startswith(). It is a function of class str, and it recieves three parameters :

  • prefix : A string or tuple which needs to be checked. Here we will be checking for substring.
  • start : An index, from where checking needs to start. It is optional. By default starts from 0th index.
  • end : An index, till where checking needs to be done. It is optional. By default uses the end of string.

This function returns True, if the calling string object starts with the given prefix and returns False if not. Let’s see an example,

# A string exampleStr = 'MSD is the Best Finisher, MSD is the only captain to win all the icc trophies of white ball cricket.' # A Substring subStr = "MSD" if exampleStr.startswith(subStr): print('Yes, string starts with the given substring') else: print('No, string does not starts with the given substring')
Yes, string starts with the given substring

In the above example, we checked whether a string starts with a given substring or not. Here “MSD” is the substring and it is present at the beginning of the string, hence startswith() returned True.

Читайте также:  Python print current dir

Check if a string starts with a substring using regex module

Another method that we can use to check whether a string starts with a substring is the match() function of the regex module in Python. The match() function accepts a regex pattern and a string as arguments. It returns a matching object if a substring is found that matches the given regex pattern, else returns None.

We can use this to check if the string starts with a given substring or not. For that we need to use the regex pattern “^subString”. Let’s see an example,

import re exampleStr = 'MSD is the Best Finisher, MSD is the only captain to win all the icc trophies of white ball cricket.' substr = "MSD" # Create regex pattern to check if string # starts with given substring pattern = "^" + substr # Check if string starts with the substring if re.match(pattern, exampleStr): print('Yes, string starts with the given substring') else: print('No, string does not starts with the given substring')
Yes, string starts with the given substring

Here we used the regex pattern “^MSD” to check if a string start with a substring “MSD” or not.

Check if a string starts with a substring using split() :

Next method that we will be using is the split() method of str class. The split() method is used to create a list of words from the string by splitting it based on a given delimeter. Here we will be using split() method to split the given string into a list of the substrings. Then we will check if the first string of the list matches with the given substring or not. If yes, then it means that the string starts with the substring. Let’s see an example,

exampleStr = 'MSD is the Best Finisher, MSD is the only captain to win all the icc trophies of white ball cricket.' substr = "MSD" # Split the string into a list of substrings wordList = exampleStr.split() # Match the first string of the list with the substring. if wordList[0] == substr: print('Yes, string starts with the given substring') else: print('No, string does not starts with the given substring')
Yes, string starts with the given substring

In the above example, we checked if a string starts with a given substring or not.

Summary

In this Python tutorial, we learned about three different methods, using which we can check whether a string starts with a substring in Python programming language. You can always use any of the methods above. But the method with the shortest syntax and is easiest to understand is method one, because you dont need to import any module or split the string. The startswith() method simply returns True if string starts with the substring.

Читайте также:  Поиск на странице

Also we have used Python 3.9.12 for writing example codes. Type python –version in your terminal to check your python version. Always try to read, write and run example codes on your machine to understand properly. Thanks.

Источник

Python String startswith() Method

The Python string method startswith() checks whether 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.

The method can also limit the search range by defining the indices where the search begins and ends, i.e. the user can decide where in the string can start the search and terminate it. So, even if the substring does not start the string, but it begins from the specified limit set, the method returns true.

Syntax

Following is the syntax for Python String startswith() method −

str.startswith(str, beg=0,end=len(string));

Parameters

  • str − This is the string to be checked.
  • beg − This is the optional parameter to set start index of the matching boundary.
  • end − This is the optional parameter to end start index of the matching boundary.

Return Value

This method returns true if found matching string otherwise false.

Example

Without passing optional parameters, the method checks whether the string input starts with the substring parameter passed. If yes, it returns true.

The following example shows the usage of Python String startswith() method. Here, we are creating a string «this is string example. wow. » and call the startswith() method on it. We pass a substring to the method as its argument and record the return value as follows —

#!/usr/bin/python str = "this is string example. wow. "; print str.startswith( 'this' ) print str.startswith( 'is' )

When we run above program, it produces following result −

Example

When we pass a substring and optional (start, end) parameters to the method, it returns true if the string input starts with the given substring from the given start index.

In this example, we create a string «this is string example. wow. «. Then, we call the startswith() method on it. We pass the substring, start and end arguments to it as follows −

str = "this is string example. wow. "; print str.startswith( 'this', 3, 10 ) print str.startswith( 'is', 2, 8 )

When we run above program, it produces following result −

Example

In the following example, we create two strings str1 = «Hello Tutorialspoint» and str2 = «Hello». Using conditional statements, we check the return value of the startswith() method, called on string str1 by passing string str2 as the argument to it.

str1 = "Hello Tutorialspoint" str2 = "Hello" if str1.startswith(str2): print("The string starts with " + str2) else: print("The string does not start with " + str2)

When we run above program, it produces following result −

The string starts with Hello

Example

In the following example we pass the substring and optional parameters, to compare with the input string; and using conditional statements, we print the return value.

str1 = "Tutorialspoint" str2 = "Tutorials" if str1.startswith(str2): print("The string starts with " + str2) else: print("The string does not start with " + str2)

When we run above program, it produces following result −

The string does not start with Tutorials

Источник

Читайте также:  Pages php lang ru

How to check if string or a substring of string starts with substring in Python?

The first approach is by using the inbuilt method startswith(). This method is used with a string, and we have to give the substring that we want to match as the parameter. Start and end are the two required parameters.

Searching begins from the start index, which is called Start, and ends at the end index, which is called End. It returns True if the given string is started with that substring, otherwise False is returned.

Example 1

In the example given below, we are taking a string and a substring as input and we are checking if the string starts with the substring using the startswith() method −

str1 = "Welcome to Tutorialspoint" substr = "Wel" print("The given string is") print(str1) print("Checking if the given string is starting with",substr) print(str1.startswith(substr))

Output

The output of the above example is given below −

The given string is Welcome to Tutorialspoint Checking if the given string is starting with Wel True

Example 2

In the example given below, we are taking the same program as above but we are taking a different substring and checking −

str1 = "Welcome to Tutorialspoint" substr = "come" print("The given string is") print(str1) print("Checking if the given string is starting with",substr) print(str1.startswith(substr))

Output

The output of the above example is as shown below −

The given string is Welcome to Tutorialspoint Checking if the given string is starting with come False

Using re module

In the second way, regular expressions are employed. To use the re library, import it and install it if it isn’t already installed. After importing the re library, we’ll utilize Regex, which interprets a prefix as the beginning of a line, so if you’re looking for a prefix, this is the way to go.

Example 1

In the example given below, we are taking a string and a substring as input and we are checking if the substring is the start of the string using Regular Expressions −

import re str1 = "Welcome to Tutorialspoint" substr = "Wel" print("The given string is") print(str1) print("Checking if the given string is starting with",substr) print(bool(re.search(substr, str1)))

Output

Following is an output of the above code −

The given string is Welcome to Tutorialspoint Checking if the given string is starting with Wel True

Example 2

In the example given below, we are taking the same program as above but we are taking a different substring and checking −

import re str1 = "Welcome to Tutorialspoint" substr = "come" print("The given string is") print(str1) print("Checking if the given string is starting with",substr) print(bool(re.search(substr, str1)))

Output

The output of the above example is given below −

The given string is Welcome to Tutorialspoint Checking if the given string is starting with come True

Источник

Оцените статью