Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python | String startswith()

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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

Python String startswith() Method Syntax

Syntax: str.startswith(prefix, start, end)

Parameters:

  1. prefix: prefix ix nothing but a string that needs to be checked.
  2. start: Starting position where prefix is needed to be checked within the string.
  3. end: Ending position where prefix is needed to be checked within the string.

Return:  Returns True if strings start with the given prefix otherwise returns False.

Python String startswith() Method Example

Here we will check if the string is starting with “Geeks” then it will return the True otherwise it will return false.

Python3




var = "Geeks for Geeks"
 
print(var.startswith("Geeks"))
print(var.startswith("Hello"))


Output:

True
False

Example 1: Python String startswith() Method Without start and end Parameters

If we do not provide start and end parameters, then Python String startswith() method will check if the substring is present at the beginning of the complete String.

Python3




text = "geeks for geeks."
 
# returns False
result = text.startswith('for geeks')
print(result)
 
# returns True
result = text.startswith('geeks')
print(result)
 
# returns False
result = text.startswith('for geeks.')
print(result)
 
# returns True
result = text.startswith('geeks for geeks.')
print(result)


Output: 

False
True
False
True

Example 2: Python String startswith() Method With start and end Parameters

If we provide start and end parameters, then startswith() will check, if the substring within start and end starts matches with the given substring.

Python3




text = "geeks for geeks."
 
result = text.startswith('for geeks', 6)
print(result)
 
result = text.startswith('for', 6, 9)
print(result)


Output:

True
True

Example 3: Checking if String starts with one of many items using Python String startswith() Method

We can also pass a tuple instead of a string to match with in Python String startswith() Method. In this case, startswith() method will return True if the string starts with any of the item in the tuple.

Python3




string = "GeeksForGeeks"
res = string.startswith(('geek', 'geeks', 'Geek', 'Geeks'))
print(res)
 
string = "apple"
res = string.startswith(('a', 'e', 'i', 'o', 'u'))
print(res)
 
string = "mango"
res = string.startswith(('a', 'e', 'i', 'o', 'u'))
print(res)


Output:

True
True
False

My Personal Notes arrow_drop_up
Last Updated : 09 Sep, 2022
Like Article
Save Article
Similar Reads
Related Tutorials