Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Check if any element in list satisfies a condition-Python
Next article icon

Python – Check if string starts with any element in list

Last Updated : 16 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We need to check if a given string starts with any element from a list of substrings. Let’s discuss different methods to solve this problem.

Using startswith() with tuple

startswith() method in Python can accept a tuple of strings to check if the string starts with any of them. This is one of the most efficient ways to solve the problem.

Python
s = "geeksforgeeks" prefixes = ["geek", "for", "python"]  # Checking if the string starts with any element in the list res = s.startswith(tuple(prefixes)) print(res)   

Output
True 

Explanation:

  • String ‘s’ is checked against a tuple of substrings from prefixes using startswith().
  • startswith() method returns True if ‘s’ starts with any of the substrings.
  • The result is stored in res and printed.

Let’s explore some more methods and see how we can check if string starts with any element in list.

Table of Content

  • Using any() and startswith()
  • Using a loop
  • Using regular expressions
  • Using filter() and lambda

Using any() and startswith()

We can use the any() function to combine the startswith() check for all elements in the list into a single line.

Python
s = "geeksforgeeks" prefixes = ["geek", "for", "python"]  # Using any to check for prefixes res = any(s.startswith(prefix) for prefix in prefixes) print(res)   

Output
True 

Explanation:

  • any() function evaluates a generator expression that checks if ‘s’ starts with each prefix.
  • If any prefix matches, the any() function returns True.
  • This approach is concise and avoids the need for an explicit loop.

Using a loop

We can iterate through the list of substrings and check if the string starts with any of them using the startswith() method.

Python
s = "geeksforgeeks" prefixes = ["geek", "for", "python"] res = False  # Iterating through the list of prefixes for prefix in prefixes:     if s.startswith(prefix):  # Checking if the string starts with the current prefix         res = True         break  # Exiting the loop as soon as a match is found print(res)   

Output
True 

Explanation:

  • We initialize res as False to indicate no match initially.
  • The for loop iterates through each substring in prefixes and checks if ‘s’ starts with it.
  • If a match is found, res is set to True, and the loop is terminated.

Using regular expressions

For more advanced cases, regular expressions can be used to match prefixes in the string.

Python
import re  s = "geeksforgeeks" prefixes = ["geek", "for", "python"]  # Creating a pattern from the list of prefixes pattern = f"^({'|'.join(re.escape(prefix) for prefix in prefixes)})" res = bool(re.match(pattern, s)) print(res)  

Explanation:

  • We construct a regular expression pattern to match any of the prefixes at the start of the string.
  • re.match() function checks if the string matches the pattern.
  • The result is converted to a boolean to indicate whether there is a match.

Using filter() and lambda

We can also use the filter() function along with a lambda to find if any prefix matches.

Python
s = "geeksforgeeks" prefixes = ["geek", "for", "python"]  # Using filter and lambda to find matches res = bool(list(filter(lambda prefix: s.startswith(prefix), prefixes))) print(res)  # 

Output
True 

Explanation:

  • lambda function checks if ‘s’ starts with each prefix.
  • filter() function applies this check to all elements in prefixes and returns matches.
  • We convert the result to a boolean to determine if any match exists.


Next Article
Check if any element in list satisfies a condition-Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python | Check if any String is empty in list
    Sometimes, while working with Python, we can have a problem in which we need to check for perfection of data in list. One of parameter can be that each element in list is non-empty. Let's discuss if a list is perfect on this factor using certain methods. Method #1 : Using any() + len() The combinati
    6 min read
  • Python | Check if suffix matches with any string in given list
    Given a list of strings, the task is to check whether the suffix matches any string in the given list. Examples: Input: lst = ["Paras", "Geeksforgeeks", "Game"], str = 'Geeks' Output: TrueInput: lst = ["Geeks", "for", "forgeeks"], str = 'John' Output: False Let's discuss a few methods to do the task
    6 min read
  • Check if any element in list satisfies a condition-Python
    The task of checking if any element in a list satisfies a condition involves iterating through the list and returning True if at least one element meets the condition otherwise, it returns False. For example, in a = [4, 5, 8, 9, 10, 17], checking ele > 10 returns True as 17 satisfies the conditio
    3 min read
  • Python | Split strings in list with same prefix in all elements
    Sometimes we face a problem in which we have a list of strings and there are some garbage/unwanted letters at its prefix or suffix or at the specified position uniformly, i.e this extends to all the strings in the list. Let's discuss certain ways in which this problem can be solved. Method #1 : Usin
    5 min read
  • Python - Check if all elements in List are same
    To check if all items in list are same, we have multiple methods available in Python. Using SetUsing set() is the best method to check if all items are same in list. [GFGTABS] Python a = [3, 3, 3, 3] # Check if all elements are the same result = len(set(a)) == 1 print(result) [/GFGTABS]OutputTrue Ex
    3 min read
  • Python | Checking if starting digits are similar in list
    Sometimes we may face a problem in which we need to find a list if it contains numbers with the same digits. This particular utility has an application in day-day programming. Let's discuss certain ways in which this task can be achieved. Method #1: Using list comprehension + map() We can approach t
    8 min read
  • Python - Check if any list element is present in Tuple
    Given a tuple, check if any list element is present in it. Input : test_tup = (4, 5, 10, 9, 3), check_list = [6, 7, 10, 11] Output : True Explanation : 10 occurs in both tuple and list. Input : test_tup = (4, 5, 12, 9, 3), check_list = [6, 7, 10, 11] Output : False Explanation : No common elements.
    6 min read
  • Python - Test if all elements in list are of same type
    When working with lists in Python, there are times when we need to ensure that all the elements in the list are of the same type or not. This is particularly useful in tasks like data analysis where uniformity is required for calculations. In this article, we will check several methods to perform th
    3 min read
  • Python - Test if string contains element from list
    Testing if string contains an element from list is checking whether any of the individual items in a list appear within a given string. Using any() with a generator expressionany() is the most efficient way to check if any element from the list is present in the list. [GFGTABS] Python s = "Pyth
    3 min read
  • Finding Strings with Given Substring in List - Python
    The task of finding strings with a given substring in a list in Python involves checking whether a specific substring exists within any of the strings in a list. The goal is to efficiently determine if the desired substring is present in any of the elements of the list. For example, given a list a =
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences