Python - Check if String Starts with list of Prefixes

With the startswit() function, we can check if a string starts with a given prefix, but most programmers use lousy ways to check with multiple prefixes.

For example:

# Not recommended
s = "Hello Python"
print(s.startswith("Javascript") or s.startswith("Javascript") or s.startswith("Hello"))

The program above is working, but this is not an excellent way to check with multi prefixes. Therefore, in this tutorial, I will show you two suitable ways to check if a string starts with any list prefixes.

How to use startswith() with multiple prefixes

In the following example, we will check if mystring starts with any of these ("Javascript", "Php", "Hello") prefixes:

my_string = "Hello Python"

# Prefixes (Tuple)
prefixes = ("Javascript", "Php", "Hello")

# Checking if starts with
c = my_string.startswith(prefixes)

# Print Output
print(c)

Output:

True

All right! The program works perfectly but, why do I use the tuple instead of the list?

The answer: Because the startswith() function does not accept a list in the first argument.

Example:

my_string = "Hello Python"

# Prefixes (List)
values = ["Javascript", "Php", "Hello"]

# Checking if starts with
c = my_string.startswith(values)

# Print Output
print(c)

Output:

TypeError: startswith first arg must be str, unicode, or tuple, not list

As demonstrated., we've got the TypeError error.

For more information about the error, visit this link How to Solve startswith first arg must be str or a tuple of str, not [bool-list-int]

However, we need to convert the list to a tuple before checking to solve this error.

Convert to a tuple using the tuple() function:

my_string = "Hello Python"

# Prefixes
prefixes = ["Javascript", "Php", "Hello"]

# Checking if starts with
c = my_string.startswith(tuple(prefixes))

# Print Output
print(c)

Output:

True

 

If you want to catch the prefix that the string starts with, follow the program below.

my_string = "Hello Python"

# Prefixes (List)
prefixes = ["Javascript", "Php", "Hello"]

for p in prefixes:
    if my_string.startswith(p):
        print(f"'{my_string}' starts with '{p}'")

Output:

'Hello Python' starts with 'Hello'

How to use startswith() with any()

The any() function helps us check the string if it starts with any list of prefixes.

The following program will show us how to use startswit() with any().

my_string = "Hello Python"

# Prefixes (List)
prefixes = ["Javascript", "Php", "Hello"]

# Checking if starts with
c = any(my_string.startswith(p) for p in prefixes)

# Print Output
print(c)

Output:

True

Conclusion

Although Python has many methods to check if the string starts with any list prefixes   , we've learned the two best ways to do this in this tutorial.

You can also use these ways with the endswith() function.