startswith() Method – Python String – with Examples


If the string begins with the supplied value, the startswith() method returns True; otherwise, it returns False.

Syntax:
string.startswith(value, start, end)

string: This is the string in which the value needs to be searched.

value: This is a required parameter. The value will be used to check whether or not the string starts with it.

start: This is an optional parameter. The start is an integer that indicates the index at which the search should begin. If not specified, the default value will be 0.

end: This is also an optional parameter. The end is an integer that indicates the index at which the search should end. If not specified, the default value will be the last string index.

The return-type of the startswith() method in Python is a boolean value.

If the value is found in the string at the specified start index (or at 0 if the start index is not specified), then the startswith() method will return True; otherwise, False.

NOTE: It is crucial to remember that Python’s startswith() method is case-sensitive with the value we provide for searching.

Example #1: Without start and end

Let’s understand the startswith() method with a simple example.

Here is the Python Code –

name = "Code Part Time"

present = name.startswith("Code")
print(present)
present = name.startswith("Co")
print(present)

# Checking it with lowercase letters
present = name.startswith("code")
print(present)

Output:

True
True
False

Example #2: Using start and end

Let’s understand the startswith() method using start and end with an example.

Here is the Python Code:

name = "Code Part Time"

present = name.startswith("Part", 5)
print(present)

present = name.startswith("art", 5, 14)
print(present)

present = name.startswith("Cod", 0, 10)
print(present)

Output:

True
False
True

Example #3: Multiple prefixes as the value in the form of a tuple

We can pass a tuple containing numerous prefixes to the startswith() method. If the string begins with any of the tuple’s items, the startswith() method returns True; otherwise, it returns False.

Here is the Python Code:

name = "Code Part Time"

prefix_tuple = ('Code', 'Time')
present = name.startswith(prefix_tuple)
print(present)

prefix_tuple = ('Part', 'Time')
present = name.startswith(prefix_tuple)
print(present)

prefix_tuple = ('Part', 'Time')
present = name.startswith(prefix_tuple, 5, 10)
print(present)

prefix_tuple = ('ode', 'tme')
present = name.startswith(prefix_tuple)
print(present)

Output:

True
False
True
False

I hope you found this article helpful.

startswith() Method – Python String – with Examples - FI

You may also like to Explore –

items() method – Python Dictionary Class

Python File close() Method – How to close a file in Python?

Python: How to Check If Key Exists In Dictionary?

Cheers!

Happy Coding.

About the Author

This article was authored by Rawnak.