Python string startswith() Method
In this tutorial, we will learn about the Python string startswith() method.
startswith() method in Python
The startswith() method in Python checks the string and return the True value if the string begins with the specific prefix else it returns the False value.
Syntax of startswith()
string_name.startswith(prefix, begin, end)
prefix: String that needs to be checked.
begin: Starting position where we check prefix in the string.
end: Terminating position where we check prefix in the string.
By default, the value of begin is 0 and the end is length-1.
Python program: string startswith() Method
text = "This code is written in Python language.\n" print("Text is: ",text) result = text.startswith('is written') # returns False print("Does the string starts with 'is written': " ) print("The Result is: ",result) result = text.startswith('This code') # returns True print("\nDoes the string starts with 'This code': " ) print("The Result is: ",result) result = text.startswith('This code is written in Python language.') # returns True print("\nDoes the string starts with 'This code is written in Python language.': " ) print("The Result is: ",result)
Output:
Text is: This code is written in Python language. Does the string starts with 'is written': The Result is: False Does the string starts with 'This code': The Result is: True Does the string starts with 'This code is written in Python language.': The Result is: True
Explanation:
In this code, first of all, we print the original string. Then, using startswith() method, one by one we check different prefixes and print the corresponding result (True or False) to it. True is returned when the string begins with the given prefix else false is returned.
I hope this will help you to solve your problem.
Also read:
Check is a string starts with a particular substring in Python
Leave a Reply