How to Check If a String Starts with a Prefix in Python
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!"
# ✅ Correct: Standard prefix check
if message.startswith("Hello"):
print("Prefix found: Hello")
else:
print("Prefix not found.")
# Checking a non-matching prefix
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"
# ✅ Correct: Checking against multiple options
# Note: You must use a tuple (), lists [] are not allowed.
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"
# ⛔️ Incorrect: Case mismatch returns False
print(f"Standard check: {message.startswith(prefix)}")
# ✅ Correct: Normalize both sides to lowercase
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"
# Check if the word "quick" starts at index 4
# "The " is 4 characters (0,1,2,3), so index 4 is 'q'
if text.startswith("quick", 4):
print("Substring 'quick' found at index 4.")
# Check within a range (index 4 to 9)
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:
- Use
startswith("prefix")for standard checks. - Pass a Tuple to check multiple prefixes at once:
startswith(("A", "B")). - Normalize Case using
.lower()if capitalization shouldn't matter. - Use Start/End Indices if you only want to check a specific slice of the string without copying it.