Computer >> Computer tutorials >  >> Programming >> Python

How to check whether a string starts with XYZ in Python?


Python has a method startswith(string) in the String class. This method accepts a prefix string that you want to search and is called on a string object. You can call this method in the following way:

>>>'hello world'.startswith('hell')
True
>>>'hello world'.startswith('nope')
False

 There is another way to find if a string ends with a given prefix. You can use re.search('^' + prefix, string) from the re module(regular expression) to do so. Regex interprets ^ as start of line, so if you want to search for a prefix,you need to do the following:

>>>import re
>>>bool(re.search('^hell', 'hello world'))
True
>>>bool(re.search('^nope', 'hello world'))
False