Check if a Substring Exists in a Python String Using in
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
The in operator is Python's simplest way to check whether a substring exists inside a string. The expression substring in text returns True when the exact sequence of characters is found and False otherwise. Both inputs must be strings; the left operand is the substring to search for, and the right operand is the string to search within.
The example defines a small helper, contains_substring(text, substring), which returns substring in text. It then tests several cases, including an empty substring, which is always considered present, and a case-insensitive check using .lower() on both values. This makes the code practical for user input, validation, and keyword detection.
Time complexity depends on the lengths of the string (n) and substring (m). A naive search is O(n * m) in the worst case, while typical performance is closer to O(n). CPython uses optimized string-search routines, so the in operator is fast for everyday use. Space complexity is O(1) because no extra data structure is required. It does not modify either string. Use in when you need a readable Boolean check; use str.find() or str.index() only when you need the position. For large text searches, benchmark if performance is critical.