Skip to content

How to Check If a String Starts with a Prefix in Python

Learn how to use Python's startswith() method to check for string prefixes, handle multiple prefixes, perform case-insensitive checks, and control search ranges efficiently.

Checking string prefixes is a fundamental task in Python, essential for parsing commands, filtering filenames, or validating data formats. The most robust way to do this is using the built-in startswith() method, which handles standard checks, tuple arguments, and slicing logic efficiently.

This guide explains how to use startswith() effectively, handle multiple prefixes, and perform case-insensitive checks.

Method 1: Using startswith() (Standard)

The startswith() string method returns True if the string begins with the specified prefix, and False otherwise.

message = "Hello, LabEx!"

if message.startswith("Hello"):
    print("Prefix found: Hello")
else:
    print("Prefix not found.")

if message.startswith("Goodbye"):
    print("Prefix found: Goodbye")
else:
    print("Prefix not found: Goodbye")

Output:

Prefix found: Hello
Prefix not found: Goodbye

Method 2: Checking Multiple Prefixes (Tuple)

Instead of writing multiple or statements (e.g., if s.startswith("Hi") or s.startswith("Hello")), you can pass a tuple of strings to startswith(). It returns True if the string starts with any of the prefixes in the tuple.

filename = "image_01.png"

if filename.startswith(("img", "image", "pic")):
    print(f"'{filename}' is a recognized image format.")
else:
    print("Unknown format.")

Output:

'image_01.png' is a recognized image format.

Method 3: Case-Insensitive Checking

The startswith() method is case-sensitive by default. To check regardless of case (e.g., matching "hello" against "Hello"), normalize both the string and the prefix to lowercase.

message = "Hello, LabEx!"
prefix = "hello"

print(f"Standard check: {message.startswith(prefix)}")

if message.lower().startswith(prefix.lower()):
    print("Case-insensitive match found!")

Output:

Standard check: False
Case-insensitive match found!

Method 4: Controlling Search Range (Start/End)

You can restrict the check to a specific substring using the optional start and end parameters. Syntax: string.startswith(prefix, start, end)

text = "The quick brown fox"

if text.startswith("quick", 4):
    print("Substring 'quick' found at index 4.")

if text.startswith("quick", 4, 9):
    print("Found within range.")

Output:

Substring 'quick' found at index 4.
Found within range.

Conclusion

To check string prefixes in Python:

  1. Use startswith("prefix") for standard checks.
  2. Pass a Tuple to check multiple prefixes at once: startswith(("A", "B")).
  3. Normalize Case using .lower() if capitalization shouldn't matter.
  4. Use Start/End Indices if you only want to check a specific slice of the string without copying it.
Navigation