Python program to check if string starts with any element in list

While working with strings, their prefixes and suffix play an important role in making any decision. For data manipulation tasks, we may need to sometimes, check if a string starts with any of the matching strings. Let’s discuss certain ways in which this task can be performed.

To check if a string starts with any element in a list in Python, we can use a simple loop that iterates over the list and checks if the string starts with each element.

Here's an example program that demonstrates this approach: 

 

def starts_with_any(string, prefixes):
    for prefix in prefixes:
        if string.startswith(prefix):
            return True
    return False

This function takes two arguments: string is the string we want to check, and prefixes is the list of prefixes we want to check against. The function iterates over each prefix in the list, and checks if the string starts with that prefix using the startswith() method. If a match is found, the function returns True. If no match is found, the function returns False.

Here's an example of how to use this function: 

 

prefixes = ['abc', 'def', 'ghi']
string1 = 'abcdefg'
string2 = 'xyz'

if starts_with_any(string1, prefixes):
    print(f"{string1} starts with one of the prefixes.")
else:
    print(f"{string1} does not start with any of the prefixes.")

if starts_with_any(string2, prefixes):
    print(f"{string2} starts with one of the prefixes.")
else:
    print(f"{string2} does not start with any of the prefixes.")

In this example, we define a list of prefixes ['abc', 'def', 'ghi'] and two strings string1 and string2. We then call the starts_with_any() function for each string, passing in the list of prefixes as the second argument. The output of the program will be: 

 

abcdefg starts with one of the prefixes.
xyz does not start with any of the prefixes.

This demonstrates how the function can be used to check if a string starts with any element in a list.

Submit Your Programming Assignment Details