python string contains
in
operator
- We Can use the keyword
in
. - It's a build-in python functionality
- Using
in
is Efficient, Clean Readable way
string = "I Love Tom & Jerry" print("Tom" in string) # True
python string contains substring
In the Above Example,
Tom
is the substring in our original stringstring
, So the result istrue
.If you search for a substring that does not exist in original string, it returns `false `.
string contains python
string = "I Love Tom & Jerry" print("Puma" in string) # False
.find()
Method
- We can use the function
find
. - Basically, it's a String method.
string = "I Love Tom & Jerry" print(string.find("Jerry")) # 13
- It Doesn't return boolean & it returns the index
- If we search for a string that doesn't exist, it returns
-1
. - It always returns the index of that substring or
-1
if that doesn't exist - We can specify the start index & stop index
string = "I Love Tom & Jerry" print(string.find("jbjb")) # -1
re
- python regex
- Uses the regular expression package
re
. - This is Advanced Method for Advanced functionality
python findall
import re string = "I Love Tom & Jerry.Tom loves Scooby" print(re.findall("Tom",string)) # ['Tom', 'Tom']
- We found all occurrences string
Tom
in our original string - This is the most PowerFul Function
- We can also use the
search
method from packagere
, It also gives an index of the string
python search
import re string = "I Love Tom & Jerry.Tom loves Scooby" print(re.search("Tom",string)) # <re.Match object; span=(7, 10), match='Tom'>
- Yes, It gives a start index & a stop index. But it doesn't find all the strings.