Python String startswith() (original) (raw)
Last Updated : 29 Apr, 2025
**startswith() method in Python checks whether a given string starts with a specific prefix. It helps in efficiently verifying whether a string begins with a certain substring, which can be useful in various scenarios like:
- Filtering data
- Validating input
- Simple pattern matching
Let’s understand by taking a simple example:
[GFGTABS]
Python
``
`s = "GeeksforGeeks" res = s.startswith("for")
print(res)
`
``
[/GFGTABS]
Explanation: startswith() method checks if the string s starts with “for“, and since it starts with “Geeks**” instead of for, the result is **False.
Syntax
string.startswith(prefix[, start[, end]])
**Parameters:
- **prefix: A string or a tuple of strings to check at the start.
- **start (optional): Index to start checking from.
- **end (optional): Index to stop checking.
**Return Type: The method returns a Boolean:
- **True if the string starts with the specified prefix.
- **False if it does not.
Examples of startswith() method
Example 1: Basic Prefix Check
Here’s a simple example where we check if a given string starts with the word “for”.
[GFGTABS]
Python
``
`s = "GeeksforGeeks"
res = s.startswith("for") print(res)
`
``
[/GFGTABS]
Explanation: The string starts with “Geeks“, so it returns **True.
Example 2: Using start Parameter
Let’s check the string using the start parameter to begin from a specific index.
[GFGTABS]
Python
``
`s = "GeeksforGeeks" print(s.startswith("for", 5))
`
``
[/GFGTABS]
Explanation: We’re checking from index 5, and “for**” starts from there hence the result is **True.
Example 3: Using start and end Parameters
We can also check for stings within a given slice using star and end parameters.
[GFGTABS]
Python
``
`s = "GeeksforGeeks" print(s.startswith("for", 5, 8))
`
``
[/GFGTABS]
**Explanation: checking only between index **5 and **8 (non inclusive) and **“for” lies in that slice, so it returns **True.
Example 4: Checking Multiple Prefixes
We can also check if the string starts with any one of several prefixes by passing a tuple of prefixes.
[GFGTABS]
Python
``
`s = "GeeksforGeeks"
res = s.startswith(("Geeks", "G")) print(res)
`
``
[/GFGTABS]
**Explanation:
- We pass a tuple with two prefixes: “Geeks” and “G”.
- The string starts with “**Geeks“, which is one of the options in the tuple, so the result is **True.