Skip to content

Python startswith list | Example code

  • by

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.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *