Python Regex – Check if string starts with specific word

Python – Check if string starts with specific word using Regex

To check if a string starts with a word in Python, use the regular expression for “starts with” ^ and the word itself.

In this tutorial, we shall use re.search() function to do an expression match against the string, and find out if the string is starting with a given word or not.

Examples

1. Check if given string starts with a specific word

In the following example, we will check if the given string Python is a programming language. starts with a specific word Python or not.

Python Program

import re

str = 'Python is a programming language.'

# Search using regex
x = re.search('^Python', str)

if(x!=None):
	print('The line starts with \'Python\'.')
else:
	print('The line does not start with \'Python\'.')
Run Code Copy

Output

The line starts with 'Python'.

If you print the output of re.search(), x, from the above example, you will get

<re.Match object; span=(0, 6), match='Python'>

2. Negative scenario

In the following example, we will check if the given string ‘Python is a programming language.’ starts with a specific word ‘programming’ or not.

Python Program

import re

str = 'Python is a programming language.'

# Search using regex
x = re.search('^programming', str)

if(x!=None):
	print('The line starts with \'programming\'.')
else:
	print('The line does not start with \'programming\'.')
Run Code Copy

Output

The line does not start with 'programming'.

If you print the output of re.search(), x, from the above example, you will get

None

If there are no matching instances for the regular expression provided, you will get None as output for re.search() function.

Summary

In this tutorial of Python Examples, we learned how to check if a string starts with a substring or word using Python Regular Expressions.

Related Tutorials

Code copied to clipboard successfully 👍