I am a newbie in Python, I am looking for the best way to check if the statement contains a specific string!
Ex: I want to check if this statement "Python is a programming language" contains a "Python" word or not!
Thanks for any inputs!
In fact, there is no a frank contains function in Python. meanwhile,
There are two ways to check if string contains specific substring in Python:-
Using “ in“ operator:
str = "Python is a programming language"
if "Python" in str
# write your code here if it true
Using” find” method that will return an index if it found the substring:
Else it return -1
Regular expression is widely used for pattern matching.
Python has a built-in package called re, which can be used to work with Regular Expressions .
The re module contains a function called search(), it can be used to check if a string contains the specified search pattern .
re.search(pattern, string, flags[optional])
Ref: Contains in Paython
Most popular tags