Python startswith list | Example code

An str.startswith method allows supplying a tuple of strings to test for Searching if a string starts with a string that is contained in a list of strings.

Python startswith list must use a tuple though

string.startswith(tuple(prefixes))

Check if a string starts with any element in the list in Python

Python example code use str.startswith() to find it a string starts with some string in a list.

In the example list of substrings has converted into a tuple using tuple(list) in order to return a boolean if str contains substrings found it.

search = ["Hello", "Hi", "Hey"]

string = "Hey World!"


print(string.startswith(tuple(search)))

Output:

Python startswith list

More Examples

print("abcde".startswith(("xyz", "abc")))

prefixes = ["xyz", "abc"]
print("abcde".startswith(tuple(prefixes)))

Output:

True
True

Do comment if you have any doubts and suggestions on this python list topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.