Skip to main content

How to Check if a String Starts With a List Element or Vice Versa in Python

Checking the beginning of strings is a frequent task in Python, often involving comparing a single string against multiple possible prefixes from a list, or checking if any string within a list starts with a specific prefix. Python's str.startswith() method, combined with tuples or iteration techniques like any() and list comprehensions, provides efficient solutions for both scenarios.

This guide demonstrates how to check if a string starts with any element from a list, and conversely, how to check if any list element starts with a specific string.

Scenario 1: Check if a String Starts With ANY Element from a List

Goal: Determine if a main string begins with at least one of the potential prefixes provided in a list.

Example Data:

main_string = "https://tutorialreference.com"
prefixes = ['http://', 'ftp://', 'https://']
non_matching_prefixes = ['www.', 'mailto:']

The str.startswith() method directly accepts a tuple of prefixes. It returns True if the string starts with any of the strings in the tuple. This is the most direct and efficient method.

main_string = "https://tutorialreference.com"
prefixes_tuple = ('http://', 'ftp://', 'https://') # Must be a tuple

# ✅ Pass the tuple of prefixes directly to startswith()
starts_with_any = main_string.startswith(prefixes_tuple)

print(f"String: '{main_string}'")
print(f"Prefixes: {prefixes_tuple}")
print(f"Starts with any prefix? {starts_with_any}") # Output: True

if starts_with_any:
print("--> String starts with one of the specified protocols.") # This runs
else:
print("--> String does not start with any specified protocol.")

# Example with non-matching prefixes
non_matching_tuple = ('www.', 'mailto:')
starts_with_any_false = main_string.startswith(non_matching_tuple)
print(f"Starts with {non_matching_tuple}? {starts_with_any_false}") # Output: False
note

You must pass a tuple to startswith(). If your prefixes are in a list, convert it first: main_string.startswith(tuple(my_list)).

Using any() with Generator Expression

This achieves the same result but checks each prefix individually using startswith() inside any(). It's slightly more verbose but demonstrates the logic.

main_string = "https://tutorialreference.com"
prefixes_list = ['http://', 'ftp://', 'https://'] # Can be a list here

# ✅ Use any() to check if startswith() is True for any prefix
starts_with_any_gen = any(main_string.startswith(prefix) for prefix in prefixes_list)

print(f"String: '{main_string}'")
print(f"Prefixes: {prefixes_list}")
print(f"Starts with any (any)? {starts_with_any_gen}") # Output: True

Getting the Matching Prefix Element (:=)

To find out which prefix matched first (requires Python 3.8+).

main_string = "https://tutorialreference.com"
prefixes_list = ['http://', 'ftp://', 'https://']
matching_prefix = None

# ✅ Use assignment expression inside any()
if any(main_string.startswith(match := prefix) for prefix in prefixes_list):
print(f"String starts with one of the prefixes!")
# 'match' holds the first prefix that satisfied startswith()
matching_prefix = match
print(f"The matching prefix is: '{matching_prefix}'") # Output: 'https://'
else:
print("String does not start with any of the prefixes.")

print(f"Final value of matching_prefix: {matching_prefix}") # Output: 'https://'

Case-Insensitive Check

Convert both the main string and each prefix to the same case before checking. startswith() doesn't have a built-in ignore case flag.

main_string_case = "FileName.TXT"
prefixes_case = ["filename.", "document.", "image."]

# ✅ Convert both to lowercase for comparison
starts_insensitive = any(main_string_case.lower().startswith(prefix.lower())
for prefix in prefixes_case)

print(f"String: '{main_string_case}'")
print(f"Prefixes: {prefixes_case}")
print(f"Starts with any (insensitive)? {starts_insensitive}") # Output: True

Scenario 2: Check if ANY Element in a List Starts With a String

Goal: Given a list of strings and a target prefix, determine if at least one string in the list begins with that prefix.

Example Data:

list_of_filenames = ["report_2023.pdf", "image_alpha.jpg", "report_2022.docx", "summary.txt"]
target_prefix = "report_"

This efficiently checks each element in the list.

list_of_filenames = ["report_2023.pdf", "image_alpha.jpg", "report_2022.docx", "summary.txt"]
target_prefix = "report_"
prefix_not_present = "data_"

# ✅ Check if any element starts with target_prefix
found_any_element = any(element.startswith(target_prefix) for element in list_of_filenames)

print(f"List: {list_of_filenames}")
print(f"Target Prefix: '{target_prefix}'")
print(f"Any element starts with prefix? {found_any_element}") # Output: True

if found_any_element:
print("--> At least one list element starts with the prefix.") # This runs
else:
print("--> No list elements start with the prefix.")


# Example with no matches
found_any_element_false = any(element.startswith(prefix_not_present) for element in list_of_filenames)
print(f"Any element starts with '{prefix_not_present}'? {found_any_element_false}") # Output: False
  • (element.startswith(target_prefix) for element in list_of_filenames): Generates True/False for each element based on whether it starts with the target_prefix.
  • any(...): Returns True if any check yields True.

Case-Insensitive Check

Convert both the element and the target prefix to the same case.

list_mixed_case = ["Apple Pie", "apricot jam", "Banana Bread"]
target_prefix_case = "app"

# ✅ Convert both to lowercase
found_any_element_insensitive = any(element.lower().startswith(target_prefix_case.lower())
for element in list_mixed_case)

print(f"List: {list_mixed_case}")
print(f"Target Prefix: '{target_prefix_case}'")
print(f"Any starts with prefix (insensitive)? {found_any_element_insensitive}") # Output: True

Scenario 3: Find ALL List Elements Starting With a String

Goal: Given a list of strings and a target prefix, create a new list containing only those strings from the original list that begin with the target prefix.

Example Data:

list_to_filter = ["user_alice", "admin_tom", "user_charlie", "guest_dave", "admin_eve"]
target_prefix = "user_"

This is the standard and most concise way to filter the list based on the condition.

list_to_filter = ["user_alice", "admin_tom", "user_charlie", "guest_dave", "admin_eve"]
target_prefix = "user_"

# ✅ Filter list using list comprehension and startswith()
matching_elements = [element for element in list_to_filter
if element.startswith(target_prefix)]

print(f"Original List: {list_to_filter}")
print(f"Target Prefix: '{target_prefix}'")
print(f"Elements starting with prefix: {matching_elements}")
# Output: Elements starting with prefix: ['user_alice', 'user_charlie']
  • [element for element in list_to_filter if element.startswith(target_prefix)]: Iterates through the list and includes element in the new list only if element.startswith(target_prefix) is True.

Case-Insensitive Check

Apply case conversion within the list comprehension.

list_mixed_case = ["Apple Pie", "apricot jam", "Banana Bread", "Apple Crumble"]
target_prefix_case = "app"

# ✅ Convert both to lowercase in the condition
matching_elements_insensitive = [element for element in list_mixed_case
if element.lower().startswith(target_prefix_case.lower())]

print(f"List: {list_mixed_case}")
print(f"Target Prefix: '{target_prefix_case}'")
print(f"Matches (insensitive): {matching_elements_insensitive}")
# Output: Matches (insensitive): ['Apple Pie', 'Apple Crumble']

Using a for Loop

A more explicit loop can build the results list.

list_to_filter = ["user_alice", "admin_tom", "user_charlie", "guest_dave", "admin_eve"]
target_prefix = "user_"
matching_elements_loop = []

print("Filtering with a loop:")
for element in list_to_filter:
if element.startswith(target_prefix):
print(f"Found match: '{element}'")
matching_elements_loop.append(element)

print(f"Final matching list (loop): {matching_elements_loop}")
# Output: Final matching list (loop): ['user_alice', 'user_charlie']

Finding Only the First Matching Element

If you only need the first element that matches, you can use a loop with break or adapt the next() function with a generator expression.

list_to_filter = ["admin_tom", "user_alice", "user_charlie"]
target_prefix = "user_"
first_match = None

# Using a loop
for element in list_to_filter:
if element.startswith(target_prefix):
first_match = element
break # Stop after first match
print(f"First match (loop): {first_match}") # Output: user_alice

# Using next()
first_match_next = next((element for element in list_to_filter if element.startswith(target_prefix)), None)
print(f"First match (next): {first_match_next}") # Output: user_alice

Conclusion

Checking if strings start with specific prefixes in Python is straightforward:

  • To check if a string starts with ANY prefix from a list/tuple: Use my_string.startswith((prefix1, prefix2, ...)) (passing a tuple). The any() function is an alternative.
  • To check if ANY string in a list starts with a prefix: Use any(element.startswith(prefix) for element in my_list).
  • To get ALL strings in a list starting with a prefix: Use a list comprehension ([element for element in my_list if element.startswith(prefix)]).

Remember startswith() is case-sensitive; use .lower() or .casefold() on both the string and the prefix/element for case-insensitive comparisons. Choose the method (startswith(tuple), any(), list comprehension) that best suits whether you need a simple boolean check or the list of actual matches.