Python – String startswith()
startswith()
method in Python is a built-in string method that 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 or validating input. In this article, we will understand about startswith() method.
Let’s understand by taking a simple example:
s = "GeeksforGeeks"
res = s.startswith("for")
print(res)
Output
False
Explanation:
- We create a string
's'
with the value"GeeksforGeeks!"
. - We then call the
startswith()
method on's'
, passing"Geeks"
as the prefix. - The method checks if the string starts with
"Geeks"
, and since it does, the result isTrue
.
Table of Content
Syntax of startswith() method
string.startswith(prefix[, start[, end]])
Parameters:
- prefix: The substring or a tuple of substrings to check for at the start of the string.
- start (optional): The index where the search for the prefix begins. By default, it starts from index 0.
- end (optional): The index where the search for the prefix ends. If not specified, the search goes till the end of the string.
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
Basic Prefix Check
Here’s a simple example where we check if the string starts with the word “Python”.
s = "GeeksforGeeks"
res = s.startswith("for")
print(res)
Output
False
- Explanation: The string starts with the word
"Python"
, so the method returnsTrue
.
Using start
and end
Parameters
Let’s check the string using the start
parameter to begin from a specific index.
s = "GeeksforGeeks"
res = s.startswith("for", 9)
print(res)
Output
False
Explanation:
- We start the check from index
9
, where"Python"
begins in the string. - The method returns
True
because the substring at that position is"Python"
.
3. Checking Multiple Prefixes
We can also check if the string starts with any one of several prefixes by passing a tuple of prefixes.
s = "GeeksforGeeks"
res = s.startswith(("Geeks", "G"))
print(res)
Output
True
Explanation:
- We pass a tuple with two prefixes:
"Geeks"
and"G"
. - Since the string starts with
"Geeks"
, the method returnsTrue
.
FAQ’s on String startswith()
Can startswith()
check multiple prefixes?
Yes, we can pass a tuple of prefixes, and it will return
True
if the string starts with any one of them.
What happens if we pass invalid start and end indices?
If the
start
orend
index is out of bounds, it will raise anIndexError
.
Does the method modify the original string?
No, the
startswith()
method only checks the prefix and returns a Boolean value. It doesn’t modify the string.