Use startswith() Function in Python with Example

The `startswith()` method in Python is used to check if a string starts with a specified prefix. It returns `True` if the string starts with the prefix, otherwise it returns `False`.

Syntax

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

– prefix: The prefix or tuple of prefixes to check for.
– start (optional): The position in the string to start checking from (default is 0).
– end (optional): The position in the string to stop checking (default is the end of the string).

Examples

Basic Usage

text = "Hello, world!"
# Check if the string starts with 'Hello'
result = text.startswith("Hello")
print(result) # Output: True
# Check if the string starts with 'world'
result = text.startswith("world")
print(result) # Output: False

With Start and End Parameters

text = "Python programming is fun."
# Check if the substring from position 0 to 10 starts with 'Python'
result = text.startswith("Python", 0, 10)
print(result) # Output: True
# Check if the substring from position 10 to the end starts with 'programming'
result = text.startswith("programming", 10)
print(result) # Output: True
# Check if the substring from position 10 to 30 starts with 'is'
result = text.startswith("is", 10, 30)
print(result) # Output: True

With Tuple of Prefixes

text = "Hello, world!"
# Check if the string starts with either 'Hi' or 'Hello'
result = text.startswith(("Hi", "Hello"))
print(result) # Output: True
# Check if the string starts with either 'Bye' or 'Goodbye'
result = text.startswith(("Bye", "Goodbye"))
print(result) # Output: False

Explanation

– Basic Usage: Checks if the entire string starts with the specified prefix.
– Start and End Parameters: Allows you to specify a substring of the original string to check for the prefix.
– Tuple of Prefixes: Checks if the string starts with any one of the prefixes provided in the tuple.

The `startswith()` method is useful for string pattern matching and validation in various programming scenarios.