Thursday, December 26, 2024
Google search engine
HomeLanguagesPython | String startswith()

Python | String startswith()

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 = "Lazyroar for Lazyroar."
 
# returns False
result = text.startswith('for Lazyroar')
print(result)
 
# returns True
result = text.startswith('Lazyroar')
print(result)
 
# returns False
result = text.startswith('for Lazyroar.')
print(result)
 
# returns True
result = text.startswith('Lazyroar for Lazyroar.')
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 = "Lazyroar for Lazyroar."
 
result = text.startswith('for Lazyroar', 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', 'Lazyroar', '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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments