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
- prefix(required) − This is the string or a tuple to be checked.
- beg(optional) − It is the start index of the matching boundary.
- end(optional) − It is the end index of the matching limit.
Return value
It returns a boolean value:
- It returns True if the string starts with the specified prefix.
- It returns False if the string doesn’t start with the specified prefix.
Visual RepresentationExample 1: How to Use String startswith() Method
str = 'Hello AppDividend'
print(str.startswith('Hello'))
Output
True
Example 2: 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
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.