

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to check if string or a substring of string starts with substring 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 >>> "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
- Related Questions & Answers
- Python Program to check if a string starts with a substring using regex
- How to check if string or a substring of string ends with suffix in Python?
- Check if substring present in string in Python
- How to check if a string contains a substring in Golang?
- How to check whether a String contains a substring or not?
- How to check if a substring is contained in another string in Python
- Java Program to Check if a string contains a substring
- PHP to check substring in a string
- How to check if the string begins with specific substring in Java?
- How to check if the string ends with specific substring in Java?
- Python Program to check if a substring is present in a given string.
- How to check if a string starts with a specified Prefix string in Golang?
- How to check if an input string contains a specified substring in JSP?
- Check if a string is entirely made of the same substring JavaScript
- Check if a string starts with given word in PHP
Advertisements