How to check if string or a substring of string starts with substring 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
>>> "Harry Potter".startswith("Harr")
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('^Harr', 'Harry Potter'))
True
>>> bool(re.search('^nope', 'hello world'))
False
raja
Published on 12-Dec-2017 06:40:02
Advertisements