# Basic syntax:any(elem in your_string for elem in elements)# Where:# - elements is an iterable# - any() will return true if any of the elements in elements is in# your_string, otherwise it returns False# Example usage:
your_string ='a short example string'any(elem in your_string for elem in['Malarkey',23,'amp'])-->True# any() returns True because amp is in your_string
string ="My favourite programming language is Python"
substring ="Python"if substring in string:print("Python is my favorite language")elif substring notin string:print("Python is not my favourite language")
s1 ='perpendicular'
s2 ='pen'
s3 ='pep'print(''pen' in 'perpendicular' -> {}'.format(s2 in s1))print(''pep' in 'perpendicular' -> {}'.format(s3 in s1))# Output# 'pen' in 'perpendicular' -> True# 'pep' in 'perpendicular' -> False# If you are more interested in finding the location of a substring within a string# (as opposed to simply checking whether or not the substring is contained),# the find() string method can be more helpful.
s ='Does this string contain a substring?'print(''string' location -> {}'.format(s.find('string')))print(''spring' location -> {}'.format(s.find('spring')))# Output# 'string' location -> 10# 'spring' location -> -1# find() returns the index of the first character of the first occurrence of the substring by default,# and returns -1 if the substring is not found
# Method that checks if a string has python keywords, function calls or assignmentsdefpythonCheck(text):if re.search(r'^(for|while|if|def|try|except|else|elif|with|continue|break|#|from|import|return|pass|async|await|yield|raise|del|class|global|finally|assert)', text):returnTrue# if it starts with a '(' then it's not pythonif re.search(r'^(', text):returnFalse# if it starts or ends with a '=' then it's not pythonif re.search(r'^=|=$', text):returnFalseif re.search(r'(|=', text):returnTruereturnFalse