Tutorial Study Image

Python startswith()

The startswith() function in python returns a boolean value. If the string starts with the specified prefix the function returns true else it returns false.


str.startswith(prefix[, start[, end]]) #where prefix may be a string or tuple
 

startswith() Parameters:

The startswith() function takes three parameters.

Parameter Description Required / Optional
prefix The value to check if the string starts with Required
start An Integer specifying at which position to start the search optional
end Ending position where prefix is to be checked within the string optional

startswith() Return Value

The return value is always a Boolean.

Input Return Value
if starts with the specified prefix True
if not starts with specified prefix False

Examples of startswith() method in Python

Example 1: How startswith() works without start and end parameters?


string = "It was a good day"

output = string.startswith('was a')
# returns False
print(output)

output = string.startswith('It was ')
# returns True
print(output)

output = string.startswith('It was a good day.')
# returns True
print(output)
 

Output:


False
True
True

Example 2: How startswith() works with start and end parameters?


string = "It was a good day."

# start parameter: 3
# 'was a good day.' string is searched
output = string.startswith('was a good day', 3)
print(output)

# start: 3, end: 7
# 'was a good' string is searched
output = string.startswith('was a good', 3, 7)
print(output)

output = string.startswith('was a good', 3, 14)
print(output) 

Output:


True
False
True