How to Check if Python String Contains a Substring?


To check if a Python string contains a given substring, use the in operator:

if "bcd" in "abcde":

To get the index of the substring if present, use the find function:

idx = "abcde".find("cd")
# the above will print 2 in this case
# it will print -1 if the substring is not found

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?