Python str.startswith() function


In Python, the str.startswith() method is used to check whether a string starts with a specified substring. This method returns True if the string starts with the specified substring and False otherwise.

Syntax

str.startswith(prefix[, start[, end]])
  • prefix: A string or a tuple of strings to check against the beginning of the string.
  • start (optional): The starting index from which to check the prefix. If omitted, the check starts from the beginning of the string.
  • end (optional): The ending index up to which to check the prefix. If omitted, the check goes to the end of the string.

Example Usage

  1. Basic usage:
text = "Hello, world!" result = text.startswith("Hello") print(result) # Output: True
  1. Using start and end parameters:
text = "Hello, world!" result = text.startswith("world", 7) # Check starting from index 7 print(result) # Output: True result = text.startswith("Hello", 0, 5) # Check within index range 0 to 5 print(result) # Output: True
  1. Checking multiple prefixes:
text = "Hello, world!" result = text.startswith(("Hi", "Hello")) print(result) # Output: True

Summary

  • Use str.startswith() to determine if a string begins with a specific substring.
  • It can also check for multiple prefixes and allows for optional starting and ending indices to refine the check.