Common Python Coding Interview Questions: Part 3

A breakdown of a common Python problem given in interviews

Robert Alterman
2 min readJul 31, 2020
Image by inspirexpressmiami from Pixabay

Write a function to check if a substring is present in a given string…

def is_present(string, substring):
if string.count(substring) > 0:
print ("Yes, the substring IS present.")
else:
print ("No, the substring is NOT present.")

Step 1: Declare the function

Since you are asked to write a function, it’s important to do so! Right away you should type ‘def’ and come up with an appropriate name for your function. Since the prompt tells you that you will be comparing two strings, be sure to include two arguments in your function declaration that will represent each string — the substring and the full string.

Step 2: Write your conditional statement

The key to solving this problem is figuring out how you can check if a string (substring) is present in another string. An easy way to do this is by using the count method, which takes in an item and checks for its occurrence in the iterable that it’s attached to, which in this case is a string. If the count is greater than zero, then that substring must be present in the string.

--

--

Robert Alterman

Data Scientist | B.S. in Information Analysis from University of Michigan School of Information | linkedin.com/in/robertalterman/ | github.com/ralterman