Python String startswith() Method

Python String startswith() method returns True if a string starts with the specified prefix. If not, it returns False. If you provide a tuple as the prefix, it returns True.

Syntax

str.startswith(prefix, beg=0,end=len(string));

Parameters

  1. prefix(required) − This is the string or a tuple to be checked.
  2. beg(optional) − It is the start index of the matching boundary.
  3. end(optional) − It is the end index of the matching limit.

Return value

It returns a boolean value:

  1. It returns True if the string starts with the specified prefix.
  2. It returns False if the string doesn’t start with the specified prefix.

Visual RepresentationVisual Representation of How to Use Python startswith() MethodExample 1: How to Use String startswith() Method

str = 'Hello AppDividend'

print(str.startswith('Hello'))

Output

True

Example 2: start and end ParametersString startswith() with start and end parameters

str = 'AppDividend'

print(str.startswith('Dividend', 3, 12))

Output

True

Example 3: startswith() With Tuple Prefix

str = "Homer Simpson is funniest characters"

result = str.startswith(('Homer', 'characters'))
print(result)

#Checking against multiple beginnings using a tuple
result_2 = str.startswith(('Bart', 'is', 'Homer', 'too'))
print(result_2)

result_3 = str.startswith(('homer', 'characters'), 10, 19)
print(result_3)

Output

True
True
False

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.