Open In App

Python - Check if string starts with any element in list

Last Updated : 16 Jan, 2025
Comments
Improve
Suggest changes
4 Likes
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.


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.

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.


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.


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.

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.


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
Practice Tags :

Similar Reads