How to check if a string contains a substring in Python?
There are multiple ways to check if a string contains a specific substring.
Using in keyword
You can use in keyword to check if a string contains a specific substring. The expression will return boolean value.
if 'Stack' in 'BetterStack': print('Found it!') else: print('Did not found it!')
The general syntax is the following:
if substring in string: # substring is in string else # substring is not in string
You can also use
String.index method to find specific the index in the string where the substring starts.
string = 'BetterStack' substring = 'Stack' try: string.index(substring) except ValueError: print('Not found!') else: print('Found it!')
Also, you can use the
find function from the String class. This function will return
-1 if the substring is not present in the string.
string = 'BetterStack' substring = 'Stack' if string.find(substring) != -1: print('Found it!') else: print('Not found!')
Understanding slicing in Python?
Slicing is a way of extracting a specific part of an array. The syntax is following: mylist[start:end] # items start through end-1 mylist[start:] # items start through the rest of the array ...Questions
Difference between static and class methods in Python?
Class method To create a class method, use the @classmethod decorator. Class methods receive the class as an implicit first argument, just like an instance method receives the instance. The class m...Questions
How to flatten a list in Python?
You can flatten a list in python using the following one-liner: flat_list = [item for sublist in l for item in sublist] In the example above, l is the list of lists that is to be flattened. The pre...Questions
What does the "yield" keyword do in Python?
To better understand what yield does, you need first to understand what generator and iterable are. What is iterable When you use a list or list-like structure, you can read the values from the lis...Questions
We are hiring.
Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.
Help us in making the internet more reliable.
Help us with developer education and get paid.
Reliability is the
Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.Explore Better Stack