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?
Let us know if you liked the post. That’s the only way we can improve.