Q&A

Questions &
Answers with MarsDevs

HTML & CSS
JavaScript

Does Python have a string 'contains' substring method?

Solution:

Yes, Python provides a method to check if a string contains a substring. 

You can use the in keyword or find() method to check. Let’s look at some examples.

If you are using the “in” keyword:


main_string = "Hello , world!"
substring = "world"

if substring in main_string:
     print("Substring found!")
else: 
     print("Substring not found.")

If you want to use the “find()” method:


main_string = "Hello , world!"
substring = "world"

if main_string.find(substring) != -1:
     print("Substring found!")
else: 
     print("Substring not found.")

If the substring exists in the main string, both techniques will return True/False. The find() method returns the index of the substring's first occurrence or -1 if the substring is not found.

Want to know more about Python tricks? Check out MarsDevs Python development blogs!