How do you check if a Python string contains a specific substring? | A1Lab@MZeeshanM to PythonEnglish •
edit-2
14 days ago

How do you check if a Python string contains a specific substring?

message-square
0

The most Pythonic and fastest way to check if a string contains a substring is by using the in membership operator, which returns True or False in linear time.

Using the in Operator (Recommended)

python
text = "Welcome to A1Lab Forum"

if "A1Lab" in text:
    print("Substring found!")

Case-Insensitive Check & Position Finding

  • Case-Insensitive: Convert both strings using .lower() or .casefold() before checking.
  • Find Index: Use text.find("A1Lab") if you need the starting index (returns -1 if missing).
python
# Case-insensitive check
exists = "a1lab" in text.lower()  # True

# Get starting index
index = text.find("Forum")        # 17