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

PythonServer Side ProgrammingProgramming

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
raja
Published on 18-Dec-2017 13:33:20
Advertisements