Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Check if Substring Exists

Test whether one string occurs inside another with membership. Students preserve substring order, see case-sensitive matching, and examine the empty-pattern rule.

IntermediatePhase 5 - Category 5: Advanced String LogicExample 2 of 14
check-if-substring-exists.py
1# Take two strings
2s1 = input("Enter first string: ")
3s2 = input("Enter second string: ")
4
5# Check substring
6if s2 in s1:
7 print(f"{s2} is substring of {s1}")
8else:
9 print(f"{s2} is not substring of {s1}")

Output

Enter first string: Hello World
Enter second string: World
World is substring of Hello World

In this one

  • Search contiguous text
  • Handle an empty pattern
  • Keep case-sensitive matching

How it works

  1. 1

    Read source s1 and candidate s2.

  2. 2

    Evaluate s2 in s1.

  3. 3

    Print whether the complete candidate is a substring.

Edge cases

Does an empty pattern match?

Does an empty pattern match?

Yes. Empty text is a substring of every string.

Does cat match Cat?

Does cat match Cat?

No. Matching is case-sensitive.

What's going on

s2 in s1 searches for the complete second string as a contiguous sequence. It does not ask whether its characters occur scattered throughout s1.

The check is case-sensitive and does not alter either response. For school and hoo, the test succeeds. An empty s2 is considered a substring of any string, including an empty one; application rules may choose to reject that input separately.

Does an empty pattern match? Yes. Empty text is a substring of every string.

Does cat match Cat? No. Matching is case-sensitive.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Must the matched characters be adjacent?

Pick an answer to check it.

Question 2

Does an empty pattern match?

Pick an answer to check it.

Questions people ask

Does an empty pattern match?

Yes. Empty text is a substring of every string.

Does cat match Cat?

No. Matching is case-sensitive.

Must the matched characters be adjacent?

Yes.