- Published on
What is `startswith()` in Python, and how is it used?
- Authors

- Name
- hwahyeon
The startswith() method is a Python string method that checks if a string starts with a specific character or substring. This method returns True or False.
Usage
string.startswith(prefix[, start[, end]])
prefix: The string (prefix) to check for at the beginning. It can be a single character, a string, or a tuple of multiple strings.start(optional): The starting index for checking. The prefix is checked from this position.end(optional): The ending index for checking. The prefix is checked up to (but not including) this position.
Basic Usage
text = "A rose by any other name would smell as sweet."
print(text.startswith("A rose")) # Output: True
print(text.startswith("Rose")) # Output: False
Checking Multiple Strings (Using a Tuple)
text = "A rose by any other name would smell as sweet."
print(text.startswith(("A rose", "The rose"))) # Output: True
print(text.startswith(("The rose", "A flower"))) # Output: False
Specifying an Index Range (Using start)
text = "The rose blooms beautifully in the garden."
print(text.startswith("rose", 4)) # Output: True
In this example, the method checks if "rose" is a prefix starting from the 4th index in text.
Example with the end Option
text = "The rose blooms beautifully in the garden."
print(text.startswith("The rose", 0, 8)) # Output: True
print(text.startswith("blooms", 0, 8)) # Output: False
In this example, the method checks only from index 0 to 8 (up to but not including index 8) to see if "The rose" is the prefix. Since this range does not contain "blooms" as the start, it returns False.