Python 3 – String startswith() Method
The startswith()
method is a built-in function used in Python 3 to check if a string starts with a specified prefix. It returns a boolean value of True
if the string starts with the specified prefix, else it returns False
. This method is useful when working with strings in Python, especially when you need to check if a particular string begins with a certain set of characters.
Syntax
The syntax of the startswith()
method in Python 3 is as follows:
string.startswith(prefix, start, end)
Parameters:
prefix
: This is the prefix that we are checking the string against.start
: This is an optional parameter and it is used to check the string from a certain index.end
: This is also an optional parameter and it is used to check the string up to a certain index.
Example 1
In this example, we will show you how to use the startswith()
method on a string to see if it starts with a certain prefix.
text = "Hello, my name is Python"
result = text.startswith("Hello")
print(result)
Output:
True
In the above example, we have a string named text
and we use the startswith()
method to check if it starts with the prefix “Hello”. Since the string does start with the prefix “Hello”, the method returns True
.
Example 2
In this example, we will use the start
and end
parameters in the startswith()
method.
text = "Python is my favorite language, Python is also easy to learn"
print(text.startswith("Python", 11))
result = text.startswith("my", 7, 15)
print(result)
Output:
True
True
In the above example, we use the startswith()
method with the parameters start
and end
. In the first example, we check if the string starts with the prefix “Python” from the 11th index of the string. This returns True
.
In the second example, we check if the string starts with the prefix “my” from the 7th index to the 15th index of the string. This also returns True
.
Conclusion
In this article, we have discussed the startswith()
method in Python 3. We have seen how it is used to check if a string starts with a certain prefix and how the start
and end
parameters are used to specify a range for checking the string. The startswith()
method is a useful tool in Python for manipulating strings and checking them for specific content.