Open In App
Related Articles

Python | String startswith()

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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

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.

String startswith() in Python Example

Here we will check if the string is starting with “Geeks” and then it will find the string begins with “Geeks” If yes then it returns True otherwise it will return false.

Python3

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

                    

Output:

True
False

Python startswith() Without start and end Parameters

If we do not provide start and end parameters, then the Python String startswith() string method will check if the string begins with present the passed substring or not.

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

Python startswith() With start and end Parameters

If we provide start and end parameters, then startswith() will check, if the substring within start and end start 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

Check if a String Starts with a Substring

We can also pass a tuple instead of a string to match within the Python String startswith() Method. In this case, startswith() method will return True if the string starts with any of the items 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


Last Updated : 20 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads