Python string startswith() example

Python string.startswith() method is used to check the start of a string for specific text patterns e.g. URL schemes and so on.

1. String startswith() example

A simple python program to check the beginning a string is to use the String.startswith().

>>> url = 'https://howtodoinjava.com'

>>> url.startswith('https:')

True		#Output

>>> url.startswith('http:')

False		#Output

2. String startswith() with tuples

If you need to check against multiple choices, simply provide a tuple of strings to startswith().

>>> filenames = ["temp.txt", "temp.ppt", "temp.doc", "temp.xls"]

>>> [name for name in filenames if name.endswith(('.doc', '.ppt')) ]

['temp.ppt', 'temp.doc']		#Output

>>> any( name.endswith('.txt') for name in filenames )

True							#Output

3. String startswith() with list or set

To use startswith(), tuple is actually required as input. If you happen to have the choices specified in a list or set, just make sure you convert them using tuple() first.

For example:

>>> choices = ['https:', 'http:', 'ftp:']

>>> url = 'https://howtodoinjava.com'

>>> url.startswith(choices)		#ERROR !! TypeError: startswith first arg must be str, unicode, or tuple, not list

>>> url.startswith( tuple(choices) )	#Correct

True							#Output

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.