Use the in operator to search for a substring in Python. 99% of use cases will be covered using the keyword,
in, which returns
if "blah" in somestring: continue
Python search for a substring Example
in comparison operator because
- the language intends its usage, and
- other Python programmers will expect you to use it.
sentence = "This be a string" sub_str = "string" if sub_str in sentence: print("Found the string.")
Using find method
If it’s just a substring search you can use string.find(“substring”).
Or use case of getting the index, use
str.find (which returns -1 on failure, and has optional positional arguments):
s = "This be a string" sub_str = "string" if s.find(sub_str) == -1: print("Not here!") else: print("Found the string.")
Found the string.
Do comment if you have any doubts and suggestions on this Python string topic/
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.