How to Check if a String Starts With a Prefix Case-Insensitively in Python

This code defines a function that checks if a string starts with a given prefix, ignoring case, using the lower() method.

Easy Python 3.9+ Aug 9, 2026 Strings & text 15 views 0 copies

Python code

17 lines
Python 3.9+
def starts_with_case_insensitive(text, prefix):
    """Check if a string starts with a given prefix, ignoring case."""
    return text.lower().startswith(prefix.lower())


if __name__ == "__main__":
    test_strings = [
        ("Hello World", "hello"),
        ("Python Programming", "PYTHON"),
        ("Data Science", "science"),
        ("Machine Learning", "ML"),
        ("", "prefix"),
    ]
    
    for text, prefix in test_strings:
        result = starts_with_case_insensitive(text, prefix)
        print(f"'{text}' starts with '{prefix}': {result}")

Output

stdout
'Hello World' starts with 'hello': True
'Python Programming' starts with 'PYTHON': True
'Data Science' starts with 'science': False
'Machine Learning' starts with 'ML': False
'' starts with 'prefix': False

How it works

The function converts both the text and the prefix to lowercase using the lower() method and then uses the built-in startswith() string method. This ensures that case differences are ignored during the comparison. Since lower() is applied to both arguments, the check works regardless of the original casing in either string. The startswith() method returns a boolean, which is useful for conditional logic.

Common mistakes

  • Forgetting to convert both the text and the prefix to lowercase, leading to case-sensitive results.
  • Using `str.lower()` on one but not the other, causing inconsistent behavior.
  • Assuming `startswith()` has a built-in case-insensitive parameter (it doesn't).

Variations

  1. Use `casefold()` instead of `lower()` for more aggressive Unicode case normalization.
  2. Use regular expressions with the `re.IGNORECASE` flag, or use `text[:len(prefix)].lower() == prefix.lower()` to avoid `startswith()` after case conversion.

Real-world use cases

  • Filtering user input like file extensions or protocol names (e.g., checking if a filename ends with '.txt' case-insensitively).
  • Validating command-line arguments where users might type 'yes', 'Yes', or 'YES'.
  • Matching URL query parameters or HTTP headers where case is not standardized.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.