Join Regular Classroom : Visit ClassroomTech

Python String – startswith() method

This is a string method in python that returns True or False if the string starts with the specified value.

Syntax:

string.startswith(value, starting_position, ending_position)

Example 1:

s = “CodeWindow offers IT related news.”
x = s.startswith(“CodeWindow“, 0, 34)
y = s.startswith(“Code“, 0, 34)
print(x)
print(y)

Output:

True
True

Explanation:

Here the string starts with “Codewindow” and also “Code”. Hence both returned True.

Example 2:

s = “CodeWindow offers IT related news.
x = s.startswith(“CodeWindow“, 5 , 34)
print(x)

Output:

False

Explanation:

Here the string starts with “CodeWindow” but the range provided is from 5 to 34-1 within which “codeWindow” doesn’t fall (Index 5 is “i”). Hence returned False.

Example 3:

s = “CodeWindow offers IT related news
x = s.startswith(“CodeWindow“, 0, 5)
print(x)

Output:

False

Explanation:

Here the string starts with only “CodeWindow” but the range provided here if from 0 to 5-1. So, “CodeWindow” as a whole doesn’t fall within that range. Hence returned False.

You Missed
Also Checkout