Python String startswith() Method – Check If a String Starts With

Python String startswith() Method

The startswith() method in Python is used to check if a string starts with a specific substring (prefix). It returns True if the string starts with the given value, and False otherwise.

Syntax

string.startswith(prefix[, start[, end]])

Parameters:

  • prefix: The substring you want to check at the beginning.
  • start (optional): The position to start checking from.
  • end (optional): The position to stop checking (not included).

Returns:

  • True if the string starts with the specified prefix; otherwise, False.

Example 1: Basic Usage

text = "hello world"
print(text.startswith("hello"))
True

Example 2: Case Sensitivity

print("Python".startswith("py"))
False

The method is case-sensitive.

Example 3: Using Start and End Parameters

msg = "Learn Python Programming"
print(msg.startswith("Python", 6))
True

It starts checking from index 6.

Example 4: Tuple of Prefixes

website = "https://example.com"
print(website.startswith(("http://", "https://")))
True

You can pass a tuple of prefixes to check against multiple options.

Common Use Cases

  • Checking if a URL starts with "https://"
  • Filtering strings by prefix (e.g., files starting with "log_")
  • Text parsing or log filtering

Common Mistakes

  • Assuming it's case-insensitive – use .lower() or .upper() to handle case.
  • Passing an empty string – returns True because every string starts with "".

Interview Tip

In interviews, startswith() is often used in filtering, log analysis, and string-matching problems.

Summary

  • startswith() checks if a string starts with a given prefix.
  • Supports optional start and end positions.
  • Returns True or False.
  • Is case-sensitive.

Practice Problem

Write a program that reads a filename from the user and checks if it starts with "img_".

filename = input("Enter filename: ")
if filename.startswith("img_"):
    print("This is an image file.")
else:
    print("Not an image file.")
Mallikarjuna Mallisetty, author
About the author

Mallikarjuna Mallisetty

General programming

Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.

View LinkedIn profile ↗