Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 26, 2021 11:43 am GMT

How to check if a python string contains a substring?

In this python tutorial, we look at how you can check if a python string contains a substring. We look at the various methods and explain their use cases in detail.

This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts. However, in case you are here only for the solution use this link.

Table of Content

Why check if a python string contains a substring?

We check if a python string contains a substring for multiple reasons, however, its most commonly used in conditional statements. This runs a code in case a substring exists and another if the python string does not contain the substring. Another common use is to find the index of the substring in the python string.

If you are coming from another language, it most likely that you have come across the contains function. Python also supports the __contains__ method, however, it also supports a few faster and more readable methods to check if a python string contains a substring.

Using the in operator:

The in operator is the most easiest and pythonic method to check if a python string contains a substring. The in and not in are membership operators, they take in two arguments and evaluate if one is a member of another. They return True in case it is a member and False in case it isn't. And hence it is used to check if a substring is a member of a python string. This is an efficient alternative to the contains method and can also be used to check if an item exists in a list.

The in is mainly used when the user only wants to check if it python string contains the substring and also because it is more readable. However, in case you are looking to return the index of the substring, the next solution is the goto.

Syntax of in:

'substring` in string

The syntax for not in is the same.

Code to check if python string contains a substring:

if "Hire" in "Hire the top freelancers":    print("Exists")else:    print("Dose not exist")#Output - Exists

The in operator is case sensitive, and the above code would've returned a false if the substring was "hire" and hence is a good practice to use it with the .lower() method. This method converts the string to lower case. As strings are immutable, this would not affect the original string.

if "hire" in "Hire the top freelancers".lower():    print("Exists")else:    print("Dose not exist")#Output - Exists

Using String Methods:

Python comes with a few string methods that can be used to check if a python string contains a substring. We look at the find() and Index() methods. These methods stand out from in as they return the index of the substring. However, they come with their cons we discuss them more in detail.

Using index()

The string.index() method returns the starting index of the substring passed as a parameter. In this way, it could be used to check if a python string contains a substring. However, a major con is that in case the substring does not exist this method returns a ValueError and hence it needs to be placed inside a Try Except.

Syntax of index():

string.index(value, start, stop)

Here string is the python string and value in the substring. The syntax also contains two optional parameters start and stop these are used in case you are looking for a substring within a particular index.

Code using index():

try:    "Hire the top freelancers".index("Hire")except ValueError:    print("Dose not exist")else:    print(sting.index(sti))#Output = 0

Similar given index() is case sensitive and using the .lower() is recommended.

try:    "Hire the top freelancers".lower().index("hire")except ValueError:    print("Dose not exist")else:    print(sting.index(sti))#Output = 0

Using find()

The string.find() is another method that can be used to check if the python string contains the substring. Similar to index() , find() also returns the starting index of the substring. But unlike the index() method it does not return a ValueError in case the substring does not exist but rather returns -1 which is the index of the left-most string.

Syntax of find():

string.find(value, start, end)

The syntax and parameters of find() are the same as index()

Code using find():

if "Hire the top freelancers".find("Hire") != -1:    print("Hire the top freelancers".find("Hire"))else:    print("Dose not exist")

And again, since find() is also case sensitive the following code can be used.

if "Hire the top freelancers".lower().find("hire") != -1:    print("Hire the top freelancers".find("Hire"))else:    print("Dose not exist")

Limitations and Caveats

  • Remember to use the .lower() methods as all the methods are case sensitive.
  • Which using the index() method to ensure it is placed inside an try and except condition.

Original Link: https://dev.to/hrishikesh1990/how-to-check-if-a-python-string-contains-a-substring-2hal

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To